Design Patterns Uncovered: The Abstract Factory Pattern

Having gone through the Factory Method pattern in the last article in this series, today we’ll take a look at Abstract Factory, the other factory pattern.

Factories in the Real World

It’s easy to think of factories in the real world – a factory is just somewhere that items gets produced such as cars, computers or TVs. Wikipedia’s definition of a real world factory is:

A factory (previously manufactory) or manufacturing plant is an industrial building where workers manufacture goods or supervise machines processing one product into another.

It’s pretty clear what a factory does, so how does the pattern work?

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Abstract Factory Pattern

The Abstract Factory is known as a creational pattern – it’s used to construct objects such that they can be decoupled from the implementing system. The definition of Abstract Factory provided in the original Gang of Four book on Design Patterns states:

Provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Now, let’s take a look at the diagram definition of the Abstract Factory pattern.

Although the concept is fairly simple, there’s a lot going on in this diagram. I’ve used red to note the different between what ConcreteFactory2 is responsible for.

The AbstractFactory defines the interface that all of the concrete factories will need to implement in order to product Products. ConcreteFactoryA and ConcreteFactoryB have both implemented this interface here, creating two seperate families of product. Meanwhile, AbstractProductA and AbstractProductB are interfaces for the different types of product. Each factory will create one of each of these AbstractProducts.

The Client deals with AbstractFactory, AbstractProductA and AbstractProductB. It doesn’t know anything about the implementations. The actual implementation of AbstractFactory that the Client uses is determined at runtime.

As you can see, one of the main benefits of this pattern is that the client is totally decoupled from the concrete products. Also, new product families can be easily added into the system, by just adding in a new type of ConcreteFactory that implements AbstractFactory, and creating the specific Product implementations.

For completeness, let’s model the Clients interactions in a sequence diagram:

While the class diagram looked a bit busy, the sequence diagram shows how simple this pattern is from the Clients point of view. The client has no need to worry about what implementations are lying behind the interfaces, protecting them from change further down the line.

Where Would I Use This Pattern?

The pattern is best utilised when your system has to create multiple families of products or you want to provide a library of products without exposing the implementation details. As you’ll have noticed, a key characteristic is that the pattern will decouple the concrete classes from the client.

An example of an Abstract Factory in use could be UI toolkits. Across Windows, Mac and Linux, UI composites such as windows, buttons and textfields are all provided in a widget API like SWT. However, the implementation of these widgets vary across platforms. You could write a platform independent client thanks to the Abstract Factory implementation.

So How Does It Work In Java?

Let’s take the UI toolkit concept on to our Java code example. We’ll create a client application that needs to create a window.

First, we’ll need to create our Window interface. Window is our AbstractProduct.

//Our AbstractProduct
public interface Window
{

    public void setTitle(String text);

    public void repaint();
}

Let’s create two implementations of the Window, as our ConcreteProducts. One for Microsoft Windows:

//ConcreteProductA1
public class MSWindow implements Window
{
   public void setTitle()
  {
     //MS Windows specific behaviour
  }

   public void repaint()
  {
     //MS Windows specific behaviour
  }
}

And one for Mac OSX

//ConcreteProductA2
public class MacOSXWindow implements Window
{
   public void setTitle()
  {
     //Mac OSX specific behaviour
  }

   public void repaint()
  {
     //Mac OSX specific behaviour
  }
}

Now we need to provide our factories. First we’ll define our AbstractFactory. For this example, let’s say they just create Windows:

//AbstractFactory
public interface AbstractWidgetFactory
{
   public Window createWindow();
}

Next we need to provide ConcreteFactory implementations of these factories for our two operating systems. First for MS Windows:

//ConcreteFactory1
public class MsWindowsWidgetFactory
{
   //create an MSWindow
   public Window createWindow()
   {
      MSWindow window = new MSWindow();
      return window;
   }
}

And for MacOSX:

//ConcreteFactory2
public class MacOSXWidgetFactory
{
   //create a MacOSXWindow
   public Window createWindow()
   {
      MacOSXWindow window = new MacOSXWindow();
      return window;
   }
}

Finally we need a client to take advantage of all this functionality.

//Client
public class GUIBuilder
{
   public void buildWindow(AbstractWidgetFactory widgetFactory)
   {
      Window window = widgetFactory.createWindow();
      window.setTitle("New Window");
   }
}

Of course, we need some way to specify which type of AbstractWidgetFactory to our GUIBuilder. This is usually done with a switch statement similar to the code below:

public class Main{
   public static void main(String[] args)
   {
     GUIBuilder builder = new GUIBuilder();
     AbstractWidgetFactory widgetFactory = null;
     //check what platform we're on
     if(Platform.currentPlatform()=="MACOSX")
     {
        widgetFactory  = new MacOSXWidgetFactory();
     }
     else
     {
           widgetFactory  = new MsWindowsWidgetFactory();
     }
     builder.buildWindow(widgetFactory);
    }
}

Just to give a clear idea of how this implementation relates to the Abstract Factory pattern, here’s a class diagram representing what we’ve just done:

Watch Out for the Downsides

While the pattern does a great job of hiding implementation details from the client, there is always a chance that the underlying system will need to change. We may have new attributes to our AbstractProduct, or AbstractFactory, which would mean a change to the interface that the client was relying on, thus breaking the API.

With both the Factory Method and today’s pattern, the Abstract Factory, there’s one thing that annoys me – someone has to determine what type of factory the client is dealing with at runtime. As you see above, this is usually done with some type of switch statement.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Factory Method Pattern

This article will focus on the Factory Method pattern, a variation on the simple factory. The Factory, as it’s name suggests, is a pattern used to facilitate the creation of other objects. In a later article we’ll be looking at the AbstractFactory.

Factories in the Real World

It’s easy to think of factories in the real world – a factory is just somewhere that items gets produced such as cars, computers or TVs. Wikipedia’s definition of a real world factory is:

A factory (previously manufactory) or manufacturing plant is an industrial building where workers manufacture goods or supervise machines processing one product into another.

It’s pretty clear what a factory does, so how does the pattern work?

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Factory Method Pattern

Factory Method is known as a creational pattern – it’s used to construct objects such that they can be decoupled from the implementing system. The definition of Factory Method provided in the original Gang of Four book on Design Patterns states:

Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses

Now, let’s take a look at the diagram definition of the Factory Method  pattern. The Creator hides the creation and instantiation of the Product from the client. This is a benefit to the client as they are now insulated from any future changes – the Creator will look after all of their creation needs, allowing to decoupling. Furthermore, once the Creator and the Product conform to an interface that the client knows, the client doesn’t need to know about the concrete implementations of either. The factory method pattern really encourages coding to an interface in order to deal with future change.

Factory Method Pattern

Here the Creator provides an interface for the creation of objects, known as the factory method. All other methods in our abstract Creator are written only to operate on the Products created in the ConcreteCreator. The Creator doesn’t create the products – that work is done by it’s subclasses, such as ConcreateCreator.

Now let’s take a look at a sequence diagram to see how this pattern behaves:

Factory Sequence Diagram

Here we see the client making a call to the abstract Creator, which then uses the factoryMethod() to get a new instance of the ConcreteProduct, complete’s the anOperation() method and completes.

Where Would I Use This Pattern?

The idea behind the Factory Method pattern is that it allows for the case where a client doesn’t know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job. The FactoryMethod builds on the concept of a simple Factory, but lets the subclasses decide which implementation of the concrete class to use.  You’ll see factories used in logging frameworks, and in a lot of scenarios where the client doesn’t need to know about the concrete implementations. It’s a good approach to encapsulation.

So How Does It Work In Java?

This example will use the concept of a logger to illustrate the factory method. First, let’s create our Product interface, in this case Logger:

//interface (Product)
public interface Logger {

	public void log(String message);
}

Next we’ll create one ConcreteProduct named XMLLogger. Obviously, we would have many different loggers

//concrete implementation of the Logger (Product)
public class XMLLogger implements Logger {

	public void log(String message) {
		//log to xml
		System.err.println("logging");
	}

}

Next, we’ll create our Creator, as a class with an abstract method that the concrete creator subclasses need to implement:

//the abstract Creator
public abstract class AbstractLoggerCreator
{
	//the factory method
	public abstract Logger createLogger();

	//the operations that are implemented for all LoggerCreators
	//like anOperation() in our diagram
	public Logger getLogger()
	{
		//depending on the subclass, we'll get a particular logger.
		Logger logger = createLogger();

		//could do other operations on the logger here

		return logger;
	}

}

The XMLLoggerCreator is our ConcreteCreator

//ConcreteCreator
public class XMLLoggerCreator extends AbstractLoggerCreator{

	@Override
	public Logger createLogger() {
		XMLLogger logger = new XMLLogger();
		return logger;
	}

}

Here’s the client code to test drive our implementation of the pattern:

public class Client {
	private void someMethodThatLogs(AbstractLoggerCreator logCreator)
	{
		Logger logger = logCreator.createLogger();
		logger.log("message");

	}

	public static void main(String[] args)
	{
		//for the purposes of this example, create an XMLLoggerCreator directly,
		//but this would normally be passed to constructor for use.
		AbstractLoggerCreator creator = new XMLLoggerCreator();

		Client client = new Client();
		client.someMethodThatLogs(creator);
	}

}

As you can see, someMethodThatLogs, takes any AbstractLoggerCreator depending on who calls the method. So, if we wanted to log to a file, or the console, we would pass through the appropriate AbstractLoggerCreator implementations.

One thing that I have left out here is the possibility to pass a paramater through to the creator in order to choose which type of concrete class to create. For example, we could have made FileLoggerCreator that could take a string parameter, allowing us to choose between XML and flat files.

Watch Out for the Downsides

One thing I would note about this approach to the Factory is that it might be overcomplicated. Perhaps the Abstract Factory is a better approach for creating objects in a decoupled manner. We’ll be discussing the Abstract Factory pattern next in the series, and will compare the two approaches then. If you want to create your own particular type of “Product” you would probably need to subclass a Creator. As with all design patterns, use it with caution, and make sure you need it.

In a lot of cases, a simple factory pattern will work fine. The FactoryMethod  just allows further decoupling, leaving it to the subclasses of the Creator to decide which type of concrete Product to create.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Command Pattern

Today’s pattern is the Command, which allows the requester of a particular action to be decoupled from the object that performs the action. Where the Chain of Responsibility pattern forwarded requests along a chain, the Command pattern forwards the request to a specific module.

Command in the Real World

One example of the command pattern being executed in the real world is the idea of a table order at a restaurant: the waiter takes the order, which is a command from the customer.This order is then queued for the kitchen staff.  The waiter tells the chef that the a new order has come in, and the chef has enough information to cook the meal.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Command Pattern

The Command pattern is known as a behavioural pattern, as it’s used to manage algorithms, relationships and responsibilities between objects. The definition of Command provided in the original Gang of Four book on Design Patterns states:

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations

So what does this mean in a class diagram?

Command declares an interface for all commands, providing a simple execute() method which asks the Receiver of the command to carry out an operation. The Receiver has the knowledge of what to do to carry out the request.  The Invoker holds a command and can get the Command to execute a request by calling the execute method. The Client creates ConcreteCommands and sets a Receiver for the command. The ConcreteCommand defines a binding between the action and the receiver. When the Invoker calls execute the ConcreteCommand will run one or more actions on the Receiver.

The following sequence diagram shows the relationship in a clearer way:

If this all seems a bit confusing right now, hang on for the code example later on in the article.

When Would I Use This Pattern?

The Command Pattern is useful when:

  • A history of requests is needed
  • You need callback functionality
  • Requests need to be handled at variant times or in variant orders
  • The invoker should be decoupled from the object handling the invocation.

You’ll see command being used a lot when you need to have multiple undo operations, where a stack of the recently executed commands are maintained. To implement the undo, all you need to do is get the last Command in the stack and execute it’s undo() method.

You’ll also find Command useful for wizards, progress bars, GUI buttons and menu actions, and other transactional behaviour.

So How Does It Work In Java?

Let’s use a remote control as the example. Our remote is the center of home automation and can control everything. We’ll just use a light as an example, that we can switch on or off, but we could add many more commands.

First we’ll create our command interface:

//Command
public interface Command
{
    public void execute();
}

Now let’s create two concrete commands. One will turn on the lights, another turns off lights:

//Concrete Command
public class LightOnCommand implementsCommand
{
    //reference to the light
    Light light;

    public LightOnCommand(Light light)
    {
        this.light = light;
    }

    public void execute()
    {
        light.switchOn();
    }

}
 //Concrete Command
public class LightOffCommand implementsCommand
{
    //reference to the light
    Light light;

    public LightOffCommand(Light light)
    {
        this.light = light;
    }

    public void execute()
    {
        light.switchOff();
    }

}

Light is our receiver class, so let’s set that up now:

//Receiver
public class Light
{
   private boolean on;

   public void switchOn()
   {
      on = true;
   }

   public void switchOff()
   {
      on = false;
   }

}

Our invoker in this case is the remote control.

//Invoker
public class RemoteControl
{
    private Command command;

    public void setCommand(Command command)
    {
        this.command = command;
    }

    public void pressButton()
    {
        command.execute();
    }

}

Finally we’ll set up a client to use the invoker

//Client
public class Client
{
    public static void main(String[] args)
    {
        RemoteControl control = new RemoteControl();

        Light light = new Light();

        Command lightsOn = new LightsOnCommand(light);
        Command lightsOff = new LightsOffCommand(light);

        //switch on
        control.setCommand(lightsOn);
        control.pressButton();

        //switch off
        control.setCommand(lightsOff);
        control.pressButton();

    }

}

Watch Out for the Downsides

This pattern ends up forcing a lot of Command classes that will make your design look cluttered – more operations being made possible leads to more command classes. Intelligence required of which Command to use and when leads to possible maintainence issues for the central controller.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

//Client
public class Client
{
    public static void main(String[] args)
    {
        RemoteControl control = new RemoteControl();

        Light light = new Light();

        Command lightsOn = new LightsOnCommand(light);
        Command lightsOff = new LightsOffCommand(light);

        //switch on
        control.setCommand(lightsOn);
        control.pressButton();

        //switch off
        control.setCommand(lightsOff);
        control.pressButton();

    }

}

Design Patterns Uncovered: The Chain Of Responsibility Pattern

Today’s pattern is the Chain of Responsibility, a simple way to decouple the handling of requests.

Chain of Responsibility in the Real World

The idea of the Chain Of Responsibility is that it avoids coupling the sender of the request to the receiver, giving more than one object the opportunity to handle the request.  This process of delegation appears quite frequently in the real world where there is one interface for the customer to go through. One example could be a bank, where an application that you send in to the bank branch may be handled by one particular department. Another example is a vending machine, where you can put in any coin, but the coin is passed on to the appropriate receptacle to determine the amount that the coin is worth. 

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Chain of Responsibility Pattern

The Chain of Responsibility is known as a behavioural pattern, as it’s used to manage algorithms, relationships and responsibilities between objects. The definition of Chain of Responsibility provided in the original Gang of Four book on Design Patterns states:

Gives more than one object an opportunity to handle a request by linking receiving objects together.

Chain of Responsibility allows a number of classes to attempt to handle a request, independently of any other object along the chain. Once the request is handled, it completes it’s journey through the chain.

Let’s take a look at the diagram definition before we go into more detail.

The Handler defines the interface required to handle request, while the ConcreteHandlers handle requests that they are responsible for.  If the ConcreteHandler cannot handle the request, it passes the request onto it’s successor, which it maintains a link to.

The objects in the chain just need to know how to forward the request to other objects.  This decoupling is a huge advantage, as you can change the chain at runtime.

Would I Use This Pattern?

This pattern is recommended when either of the following scenarios occur in your application:

  • Multiple objects can handle a request and the handler doesn’t have to be a specific object
  • A set of objects should be able to handle a request with the handler determined at runtime
  • A request not being handled is an acceptable outcome.

The pattern is used in windows systems to handle events generated from the keyboard or mouse. Exception handling systems also implement this pattern, with the runtime checking if a handler is provided for the exception through the call stack. If no handler is defined, the exception will cause a crash in the program, as it is unhandled.

In JavaEE, the concept of Servlet filters implement the Chain of Responsibility pattern, and may also decorate the request to add extra information before the request is handled by a servlet.

So How Does It Work In Java?

Now let’s take a look at how we might implement the Chain of Responsibility with a code example. Let’s use an email client as an example. You might set up some rules to move a message into a particular folder depending on who it’s from. First we’ll need to create our EmailHandler interface.

//Handler
public interface EmailHandler
{
	//reference to the next handler in the chain
	public void setNext(EmailHandler handler);

	//handle request
	public void handleRequest(Email email);
}

Now let’s set up two concrete handlers, one for business mail and one for email originating from Gmail. These handlers pass on the request if it doesn’t interest them

public class BusinessMailHandler implements EmailHandler
{
	private EmailHandler next;

	public void setNext(EmailHandler handler)
	{
	    next = handler;
	}

	public void handleRequest(Email email)
    {
		if(!email.getFrom().endsWith("@businessaddress.com")
		{
		    next.handleRequest(email);
		}
		else
		{
		    //handle request (move to correct folder)
		}

	}	

}
public class GMailHandler implements EmailHandler
{
	private EmailHandler next;

	public void setNext(EmailHandler handler)
	{
	    next = handler;
	}

	public void handleRequest(Email email)
    {
		if(!email.getFrom().endsWith("@gmail.com")
		{
		    next.handleRequest(email);
		}
		else
		{
		    //handle request (move to correct folder)
		}

	}	

}

Now let’s set up a client that manages the handlers – this will actually be our EmailProcessor.

public class EmailProcessor
{
	//maintain a reference to the previous handler so we can add the next one
	private EmailHandler prevHandler;

	public void addHandler(EmailHandler handler)
	{
		if(prevHandler != null)
		{
			prevHandler.setNext(handler);
		}
		prevHandler = handler;
	}

}

This class allows us to add in new handlers at any stage. Finally, the email client itself uses the EmailProcessor to look after all incoming messages

//email client 

public class EmailClient
{
	private EmailProcessor processor; 

	public EmailClient()
	{
	   createProcessor();

	}

	private void createProcessor()
	{
		processor = new EmailProcessor();
		processor.addHandler(new BusinessMailHandler());
		processor.addHandler(new PersonalMailHandler());
	}

	public void addRule(EmailHandler handler)
	{
	   processor.addHandler(handler);
	}

	public void emailReceived(Email email)
	{
		processor.handleRequest(email);
	}

	public static void main(String[] args)
	{

		EmailClient client = new EmailClient();

	}

}

If new rules, for forwarding email to particular folders are added, we can add the handler to our email processor at runtime using the addRule() method in the client.

Watch Out for the Downsides

As with the Observer pattern, Chain of Responsibility can make it difficult to follow through the logic of a particular path in the code at runtime. It’s also important to note that there is the potential that the request could reach the end of the chain and not be handled at all.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Inspiration For Your Mobile Applications

So you know exactly what you want your mobile application to do, but you’re not sure how to design the screens.  Usually, there’s an app out there that’s done something similar. I found two great sites that provide screenshots of popular mobile applications, providing ideas for everything from splash screens to profile pages, lists to sign-up flows.

Both sites are worth bookmarking for those times when inspiration dries up.

Design Patterns Uncovered: The Interpreter Pattern

Today’s pattern is the Interpreter pattern, which defines a grammatical representation for a language and provides an interpreter to deal with this grammar.

Interpreter in the Real World

The first example of interpreter that comes to mind, is a translator, allowing people to understand a foreign language. Perhaps musicians are a better example: musical notation is our grammar here, with musicians acting as interpreters, playing the music.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Interpreter Pattern

The Interpreter pattern is known as a behavioural pattern, as it’s used to manage algorithms, relationships and responsibilities between objects.. The definition of Interpreter as provided in the original Gang of Four book on Design Patterns states:

Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language.

The following diagram shows how the interpreter pattern is modelled.

Context contains information that is global to the interpreter. The AbstractExpression provides an interface for executing an operation. TerminalExpression implements the interpret interface associated with any terminal expressions in the defined grammar.

The Client either builds the Abstract Syntax Tree, or the AST is passed through to the client. An AST is composed of both TerminalExpressions and NonTerminalExpressions. The client will kick off the interpret operation. Note that the syntax tree is usually implemented using the Composite pattern

The pattern allows you to decouple the underlying expressions from the grammar.

When Would I Use This Pattern?

The Interpreter pattern should be used when you have a simple grammar that can be represented as an Abstract Syntax Tree. This is the more obvious use of the pattern. A more interesting and useful application of Interpreter is when you need a program to produce different types of output, such as a report generator.

So How Does It Work In Java?

I’ll use a simple example to illustrate this pattern. We’re going to create our own DSL for searching Amazon. To do this, we’ll need to have a context that uses an Amazon web service to run our queries.

//Context
public class InterpreterContext
{
	//assume web service is setup
	private AmazonWebService webService;

	public InterpreterContext(String endpoint)
	{
		//create the web service.
	}

	public ArrayList<Movie> getAllMovies()
	{
	   return webService.getAllMovies();
	}

	public ArrayList<Book> getAllBooks()
	{
	  return webService.getAllBooks();

	}
}

Next, we’ll need to create an abstract expression:

//Abstract Expression
public abstract class AbstractExpression
{
   public abstract String interpret( InterpreterContext context);
}

We’ll have many different expressions to interpret our queries. For illustration,let’s create just one:

//Concrete Expression
public class BookAuthorExpression extends AbstractExpression
{

	private String searchString;

   public BookAuthorExpression(String searchString)
   {
		this.searchString = searchString;
   }

   public String interpret(InterpreterContext context)
   {
		ArrayList<Book> books = context.getAllBooks();
		StringBuffer result = new StringBuffer();
		for(Book book: books)
		{
			 if(book.getAuthor().equalsIgnoreCase(searchString))
			 {
				result.append(book.toString());
			 }
		}
		return result;

   }

}

Finally, we need a client to drive all of this. Let’s assume that our language is of the following type of syntax:

books by author 'author name'

The client will determine which expression to use to get our results:

//client
public class AmazonClient
{

 private InterpreterContext context;

 public AmazonClient(InterpreterContext context)
 {
	this.context = context;
 }

 /**
  * Interprets a string input of the form
  *   movies | books by title | year | name '<string>'
  */
 public String interpret(String expression)
 {
	//we need to parse the string to determine which expression to use 

	AbstractExpression exp = null; 

	String[] stringParts = expression.split(" ");

	String main = stringParts[0];
	String sub = stringParts[2];

	//get the query part
	String query = expression.substring(expression.firstIndexOf("'"), expression.lastIndexOf("'"));

	if(main.equals("books"))
	{
		if(sub.equals("title")
		{
		  exp = new BookTitleExpression(query);
		}
		if(sub.equals("year")
		{
		   exp = new BookYearExpression(query);
		}
	}
	else  if(main.equals("movie"))
		  {
			//similar statements to create movie expressions
		  }

	if(exp != null)
	{
		exp.interpret(context);
	}

 }

 public static void main(String[] args)
 {
	InterpreterContext context  = new InterpreterContext("http://aws.amazon.com/");
	AmazonClient client = new AmazonClient();

	//run a query
	String result = client.interpret("books by author 'John Connolly'");

	System.out.println(result);
 }

}

I admit the example is a bit simple, and you would probably have a more intelligent context, but that should give you the idea of how this pattern works.

Watch Out for the Downsides

Efficiency is a big concern for any implementation of this pattern. Introducing your own grammar requires extensive error checking, which will be time consuming for the programmer to implement, and needs careful design in order to run efficiently at runtime. Also, as the grammar becomes more complicated, the maintainence effort is increased.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Facade Pattern

This article will focus on the Facade pattern. So far in our design patterns we’ve already looked at the Observer and Adapter patterns. Facade has some similarities with the Adapter, so it’s a logical next step in our series.

Facades in the Real World

Facades are all around us in the real world.  Operating systems are one such example – you don’t see all the inner workings of your computer, but the OS provides a simplified interface to use the machine. Buildings also have a facade – the exterior of the building. Wikipedia gives us a nice link between software architecture and standard architecture:

In architecture, the facade of a building is often the most important from a design standpoint, as it sets the tone for the rest of the building

So, in a nutshell, a Facade aims to make things look cleaner and more appealling.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Facade Pattern

Like the Adapter pattern, Facade is known as a structural pattern, as it’s used to identifying a simple way to realize relationships between entities. The definition of Facade provided in the original Gang of Four book on Design Patterns states:

Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.

The diagram definition of the Facade pattern is quite simple – all you’re really doing is insulating client from the subsystem:

Facade Pattern

Like the adapter pattern, the Facade can be used to hide the inner workings of a third party library, or some legacy code.  All that the client needs to do is interact with the Facade, and not the subsystem that it is encompassing.

The following sequence diagram illustrates how the pattern is used by a client:

Facade Pattern Sequence Diagram

Where Would I Use This Pattern?

As the concept behind facade is to simplify an interface, service oriented architectures make use of the facade pattern. For example, in web services, one web service might provide access to a number of smaller services that have been hidden from the caller by the facade. Similarly, a typical pattern in OSGi bundles is to provide an interface package that is exposed to users of the bundle. All other packages are hidden from the user.

So How Does It Work In Java?

Let’s put together a simple example in Java code to illustrate the pattern. Let’s take a travel agent site for example, that allows you to book hotels and flights. We have a HotelBooker:

public class HotelBooker
{

  public ArrayList<Hotel> getHotelNamesFor(Date from, Date to)
  {
      //returns hotels available in the particular date range

  }

}

And a FlightBooker:

public class FlightBooker
{

  public ArrayList<Flight> getFlightsFor(Date from, Date to)
  {
      //returns flights available in the particular date range

  }

}

Both of these have Hotel and Flight datatypes, which the client has knowledge about. They could be provided in the same package as the Facade for example.

The TravelFacade class allows the user to get their Hotel and Flight information in one call:

public class TravelFacade
{

   private HotelBooker hotelBooker;
   private FlightBooker flightBooker; 

  public void getFlightsAndHotels(Date from, Data to)
  {
         ArrayList<Flight> flights = flightBooker.getFlightsFor(from, to);
         ArrayList<Hotel> hotels = hotelBooker.getHotelsFor(from, to);

         //process and return

   }

}

All that the client needs to worry about is the Facade class:

public class Client
{

   public static void main(String[] args)
   {
        TravelFacade facade = new TravelFacade();
        facade.getFlightsAndHotels(from, to);
   }
}

As you can see, it’s just a simple approach to encapsulating data.

Watch Out for the Downsides

By introducing the Facade into your code, you will be hardwiring subsystems into the Facade. This is fine if the subsystem never changes, but if it does, your Facade could be broken. Therefore, developers working on the subsystem should be made aware of any Facade around their code.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Adapter Pattern

Continuing our series of articles, taking each design pattern one by one, we move onto the Adapter pattern. This pattern is used a lot in Eclipse, allowing plug-ins to be loosely coupled, yet still be integrated into the Eclipse runtime.

Adapters in the Real World

A real world analogy always helps with the understanding of a design pattern. The best example for the adapter pattern is based around AC power adapters. Say you’re visiting Europe from the US, with your laptop, which expects a US power supply. To get your laptop plugged in, you’re going to need to get a power adapter that accepts your US plug and allows it to plug in to the European power outlet. The AC adapter knows how to deal with both sides, acting as a middleman – this is the adapter pattern.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Adapter Pattern

The Adapter is known as a structural pattern, as it’s used to identifying a simple way to realize relationships between entities. The definition of Adapter provided in the original Gang of Four book on Design Patterns states:

Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.

Let’s take a look at the classic diagram definition of  the adapter pattern:

Adapter Pattern

The Target interface defines the domain specific interface that the Client used, so the client collaborates with objects that implement the Target interface. On the other side of things, the Adaptee is the existing interface that needs adapting in order for our client to interact with it. The Adapter adapts the Adaptee to the Target interface – in other words, it translates the request from the client to the adaptee.

Let’s take a look at the interactions in a sequence diagram:

Adapter Sequence Diagram

In this example, as far as the Client is concerned it’s just calling the request method of the Target interface, which the Adapter has implemented. In the background however, the Adapter knows that to return the right result, it needs to call a different method, specificAdapteeRequest, on the Adaptee.

Note: the pattern described here is the object adapter. There is a class adapter pattern, but you need multiple inheritance to use it. Seeing as Java doesn’t support multiple inheritance, I’m going to leave this out.

Where Would I Use This Pattern?

The main use of this pattern is when a class that you need to use doesn’t meet the requirements of an interface. As mentioned before, adapters are common across Eclipse plug-ins. For a particular object to contribute to the Properties view, adapters are used display the objects data. The view itself doesn’t need to know anything about the object the it is displaying properties for.

So How Does It Work In Java?

The following example shows a simple implementation of the pattern. Consider that we have a third party library that provides sorting functionality through it’s NumberSorter class. This is our Adaptee.

/*
 * This is our adaptee, a third party implementation of a
 * number sorter that deals with Lists, not arrays.
 */
public class NumberSorter
{
   public List<Integer> sort(List<Integer> numbers)
   {
      //sort and return
      return new ArrayList<Integer>();
   }

}

Our Client deals with primitive arrays rather than Lists. For the sake of this example, lets say we can’t change the client to use Lists.

int[] numbers = new int[]{34, 2, 4, 12, 1};

Sorter sorter = new SortListAdapter();
sorter.sort(numbers);

We’ve provided a Sorter interface that expects the client input. This is our target.

//this is our Target interface
public interface Sorter
{
   public int[] sort(int[] numbers);
}
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter
public class SortListAdapter implements Sorter
{

   @Override
   public int[] sort(int[] numbers)
   {
      //convert the array to a List
      List<Integer> numberList = new ArrayList<Integer>();

      //call the adapter
      NumberSorter sorter = new NumberSorter();
      numberList = sorter.sort(numberList);

      //convert the list back to an array and return 

      return sortedNumbers;
   }

}

While this example may be overkill, it illustrates how the adapter pattern can work.

Watch Out for the Downsides

Some say that the Adapter pattern is just a fix for a badly designed system, which didn’t consider all possibilties. While this is a fair point, it is an important part of a pluggable architecture.  It can also add a level of complexity to your code, making debugging more difficult.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Visitor Pattern

Today we’re going to take a look at the Visitor pattern. Of all of the patterns that I’ve used so far, Visitor is by far the most powerful and convenient.

Vistors in the Real World

A real world analogy always helps with the understanding of a design pattern. One example I have seen for the Visitor pattern in action is a taxi example, where the customer calls orders a taxi, which arrives at his door. Once the person sits in, the visiting taxi is in control of the transport for that person.

Shopping in the supermarket is another common example, where the shopping cart is your set of elements. When you get to the checkout, the cashier acts as a visitor, taking the disparate set of elements (your shopping), some with prices and others that need to be weighed, in order to provide you with a total.

It’s a difficult pattern to explain in the real world, but things should become clearer as we go through the pattern definition, and take a look at how to use it in code.

Design Patterns Refcard
For a great overview of the most popular design patterns, DZone’s Design Patterns Refcard is the best place to start.

The Visitor Pattern

The Visitor is known as a behavioural pattern, as it’s used to manage algorithms, relationships and responsibilities between objects. The definition of Visitor provided in the original Gang of Four book on Design Patterns states:

Allows for one or more operation to be applied to a set of objects at runtime, decoupling the operations from the object structure.

What the Visitor pattern actually does is create an external class that uses data in the other classes. If you need to perform operations across a dispate set of objects, Visitor might be the pattern for you. The GoF book says that the Visitor pattern can provide additional functionality to a class without changing it. Let’s see how that can work, first by taking a look at the classic diagram definition of  the Visitor pattern:

Visitor Pattern

The core of this pattern is the Visitor interface. This interface defines a visit operation for each type of ConcreteElement in the object structure. Meanwhile, the ConcreteVisitor implements the operations defined in the Visitor interface. The concrete visitor will store local state, typically as it traverses the set of elements. The element interface simply defines an accept method to allow the visitor to run some action over that element – the ConcreteElement will implement this accept method.

Where Would I Use This Pattern?

The pattern should be used when you have distinct and unrelated operations to perform across a structure of objects. This avoids adding in code throughout your object structure that is better kept seperate, so it encourages cleaner code. You may want to run operations against a set of objects with different interfaces.  Visitors are also valuable if you have to perform a number of unrelated operations across the classes.

In summary, if you want to decouple some logical code from the elements that you’re using as input, visitor is probably the best pattern for the job.

So How Does It Work In Java?

The following example shows a simple implementation of the pattern in Java. The example we’ll use here is a postage system. Our set of elements will be the items in our shopping cart. Postage will be determined using the type and the weight of each item, and of course depending on where the item is being shipped to.

Let’s create a seperate visitor for each postal region. This way, we can seperate the logic of calculating the total postage cost from the items themselves. This means that our individual elements don’t need to know anything about the postal cost policy, and therefore, are nicely decoupled from that logic.

First, let’s create our general visitable  interface:

//Element interface
public interface Visitable
{
    public void accept(Visitor visitor);
}

Now, we’ll create a concrete implementation of our interface, a Book.

//concrete element
public class Book implements Visitable
{
   private double price;
   private double weight;

   //accept the visitor
   public void accept(Visitor vistor)
   {
      visitor.visit(this);
   }

   public double getPrice()
   {
      return price;
   }

   public double getWeight()
   {
      return weight;
   }
}

As you can see it’s just a simple POJO, with the extra accept method added to allow the visitor access to the element. We could add in other types here to handle other items such as CDs, DVDs or games.

Now we’ll move on to the Visitor interface. For each different type of concrete element here, we’ll need to add a visit method. As we’ll just deal with Book for now, this is as simple as:

public interface Visitor
{
   public void visit(Book book);
   //visit other concrete items
   public void visit(CD cd);
   public void visit(DVD dvd);
}

The implementation of the Vistor can then deal with the specifics of what to do when we visit a book.

public class PostageVisitor implements Visitor
{
   private double totalPostageForCart;
   //collect data about the book
    public void visit(Book book)
    {
      //assume we have a calculation here related to weight and price
      //free postage for a book over 10
      if(book.getPrice() < 10.0)
      {
         totalPostageForCart += book.getWeight() * 2;
      }
    }

    //add other visitors here
    public void visit(CD cd){...}
    public void visit(DVD dvd){...}
    //return the internal state
    public double getTotalPostage()
    {
      return totalPostageForCart;
    }
}

As you can see it’s a simple formula, but the point is that all the calculation for book postage is done in one central place.

To drive this visitor, we’ll need a way of iterating through our shopping cart, as follows:

public class ShoppingCart
{
   //normal shopping cart stuff
   private ArrayList<Visitable> items;

   public double calculatePostage()
  {
      //create a visitor
      PostageVisitor visitor = new PostageVisitor();
      //iterate through all items
      for(Visitable item: items)
      {
         item.accept(visitor);
      }
     double postage = visitor.getTotalPostage();
     return postage;

  }

}

Note that if we had other types of item here, once the visitor implements a method to visit that item, we could easily calculate the total postage.

So, while the Visitor may seem a bit strange at first, you can see how much it helps to clean up your code. That’s the whole point of this pattern – to allow you seperate out certain logic from the elements themselves, keeping your data classes simple.

Watch Out for the Downsides

The arguments and return types for the visiting methods needs to be known in advance, so the Visitor pattern is not good for situtations where these visited classes are subject to change. Every time a new type of Element is added, every Visitor derived class must be amended.

Also, it can be difficult to refactor the Visitor pattern into code that wasn’t already designed with the pattern in mind. And, when you do add your Visitor code, it can look obscure. The Visitor is powerful, but you should make sure to use it only when necessary.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.

Design Patterns Uncovered: The Observer Pattern

Design patterns are one of the most valuable tools for developers. They illustrate the best design solutions that others have encountered, and allow you to apply the same principle to your own designs. More importantly, knowing design patterns gives a common vocabulary for software developers to use when talking about their designs.

In this article series, I’ll be going through each pattern and describing how it’s used and where it’s applied in the real world. To start off, I’ll be describing one of the most used design patterns, the Observer pattern.

The Observer In The Real World

Before we get into the theory and code behind the Observer, let’s take a look at a real world example, such as RSS feeds. When I want to get updates from a particular feed, I add it to my feed reader. Any time that the RSS feed has an update, it will appear in my reader automatically. This is the Observer pattern in action, a publisher/subscriber relationship with one source having many subscribers.

The Observer Pattern

Of all of the design patterns that are out there, the Observer is one that you’ve probably used already, even if you weren’t aware of it. The Observer pattern is the gold standard in decoupling – the seperation of objects that depend on each other.

The Observer is known as a behavioural pattern, as it’s used to form relationships between objects at runtime. The definition provided in the original Gang of Four book on Design Patterns states:

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

Let’s take a look at the classic diagram definition of the observer:

The idea behind the pattern is simple – one of more Observers are interested in the state of a Subject and register their interest with the Subject by attaching themselves. When something changes in our Subject that the Observer may be interested in, a notify message is sent, which calls the update method in each Observer.
When the Observer is no longer interested in the Subject’s state, they can simply detatch themselves. The following sequence diagram illustrates the registration and notification flow in action.

The benefits here are quite clear. To pass data onto the observers, our subject doesn’t need to know who needs to know. Instead, everything is done through a common interface, and the notify method just calls all the objects out there that have registered their interest. This is a very powerful decoupling – meaning that any object can simply implement the Observer interface and get updates from the Subject.

Where Would I Use This Pattern?

In general, you want to use this pattern to reduce coupling. If you have an object that needs to share it’s state with others, without knowing who those objects are, the Observer is exactly what you need.

You’ll have seen, and probably used, the Observer many times if you’ve done any UI programming, especially in Swing. The whole concept of listeners is based on this pattern. The event listener is the most popular, where you register an ActionListener to a UI control, such a button, and react to action events using the actionPerformed method. In this case, the ActionListener is the Observer and the button is your Subject. As the button changes state, you can react, if you choose to, in your actionPerformed method.

The typical real world uses of the pattern all revolve around this type of event handling system.

So How Does It Work In Java?

While some patterns require you to define the interfaces that make the pattern work, the Observer is a case where Java has the work done for you already in the java.util package.

The slight difference from the classic definition is that Observable is used in place of the Subject and is implemented as a class, while the Observer interface remains the same. Let’s take a look at an implementation of the pattern with a real example. In our example, the subject will be a DataStore, with a Screen class as the observer.

First, let’s make our DataStore class observable by extending the java.util.Observable class. This means that our DataStore has all the methods and functionality available to make it a Subject, according to our pattern.

import java.util.Observable;

public class DataStore extends Observable
{

	private String data;

	public String getData()
	{
		return data;
	}

	public void setData(String data)
	{
		this.data =data;
		//mark the observable as changed
		setChanged();
	}
}

You’ll notice that we have called the setChanged() method of the Observable. This is necessary in order for the call to notify observers to send out the update. Without this set, the Observable will see no reason to send out the update.

Next, let’s create our Observer. To do this, all we need to do is implement the Observer interface which forces us to write an update method, to deal with changes in the Observable’s state.

public class Screen implements Observer {

	@Override
	public void update(Observable o, Object arg) {

		//act on the update
	}

}

Adding our Screen as an observer to the DataStore is simple:

Screen screen = new Screen();

DataStore dataStore = new DataStore();
//register observer
dataStore.addObserver(screen);

When the data changes, we want to notify all observers of this object. To do this, we just need to call the notifyObservers method when we want an update sent out

//send a notification
dataStore.notifyObservers();

As you can see it’s a really simple pattern to understand, and even easier to use thanks to the Java implementation of the pattern.

Watch Out for the Downsides

As with any piece of code, you need to be careful how you use the Observer pattern. Martin Fowler has a good list of gotchas for the observer. In his article he mentions that it can be difficult to see the path through the code, unless you are debugging. As such, you should be careful not to have chains of observers (observers acting as subjects). Also, watch out for memory leaks as the subject will hold a reference to the observer unless it has deregistered.

Find Out More


The classic Design Patterns: Elements of Reusable Object Oriented Software
For more practical Java examples: Head First Design Patterns.