Design Patterns Uncovered: The Bridge Pattern

Today’s pattern is the Bridge pattern, which allows you to vary both the implementation and the abstraction by placing both in seperate class hierachies.

Bridge in the Real World

The display of different image formats on different operating systems is a good example of the Bridge pattern. You might have different image abstractions for both jpeg and png images. The image structure is the same across all operating systems, but the how it’s viewed (the implementation) is different on each OS. This is the type of decoupling that the Bridge pattern allows.

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 Bridge Pattern

The Bridge pattern is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Bridge provided in the original Gang of Four book on Design Patterns states:

Decouple an abstraction from its implementation so that the two can vary independently

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

The Abstraction defines the abstraction, and maintains the reference to the implementor.  RefinedAbstraction provides an extension to the Abstraction, usually adding extra methods that provide different ways of getting at the same functionality. The Implementor interface defines an interface for the implementation classes (the ConcreateImplementorclasses).
RefinedAbstractions are implemented in terms of the abstraction, and not that implementation interface.This means that the implementation details are hidden from the client. The pattern is similar to the Adapter pattern, except the Bridge pattern separates the interface from implementation.

Would I Use This Pattern?

The Bridge pattern should be used when both the class as well as what it does vary often. The bridge pattern can also be thought of as two layers of abstraction. When the abstractions and implementations should not be bound at compile time, and should be independently extensible the pattern should be used.

In particular this pattern is useful in graphic toolkits that need to run on multiple platforms. You’ll  see this in AWT, where a component has a component peer which does the OS specific operations. Also the Collections framework has examples of the bridge interface: ArrayList and LinkedList are implement List. And List provides common methods to add, remove or check size.

So How Does It Work In Java?

Here’s the pattern in action using the remote control example from Head First Design Patterns.

First, we have our TV implementation interface:

//Implementor
public interface TV
{
	public void on();
	public void off();
	public void tuneChannel(int channel);
}

And then we create two specific implementations – one for Sony and one for Philips:

//Concrete Implementor
public class Sony implements TV
{
	public void on()
	{
		//Sony specific on
	}

	public void off()
	{
		//Sony specific off
	}

	public void tuneChannel(int channel);
	{
		//Sony specific tuneChannel
	}
}

//Concrete Implementor
public class Philips implements TV
{
	public void on()
	{
		//Philips specific on
	}

	public void off()
	{
		//Philips specific off
	}

	public void tuneChannel(int channel);
	{
		//Philips specific tuneChannel
	}
}

These classes deal with the specific implementations of the TV from each vendor.

Now, we create a remote control  abstraction to control the TV:

//Abstraction
public abstract class RemoteControl
{
   private TV implementor; 

   public void on()
   {
      implementor.on();
   }
   public void off()
   {
      implementor.off();
   }

   public void setChannel(int channel)
   {
	   implementor.tuneChannel(channel);
   }
}

As the remote control holds a reference to the TV, it can delegates the methods through to the interface. But what is we want a more specific remote control – one that has the + / – buttons for moving through the channels? All we need to do is extend our RemoteControl abstraction to contain these concepts:

//Refined abstraction
public class ConcreteRemote extends RemoteControl
{
   private int currentChannel; 

   public void nextChannel()
   {
       currentChannel++;
	   setChannel(currentChannel);
   }

   public void prevChannel()
   {
       currentChannel--;
	   setChannel(currentChannel);
   }

}

Watch Out for the Downsides

One of the major drawbacks of this pattern is that, in providing flexibility, it increases complexity. There’s also possible performance issues with the indirection of messages – the abstraction needs to pass messages along to the implementator for the operation to get executed.

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 Builder Pattern

Today’s pattern is the Builder pattern,which allows for dynamic creation of objects based upon interchangable algorithms.

Builder in the Real World

The purpose of the builder pattern is to separate the construction of a complex object from its representation. so that the same construction process can create different representation. An example of this is happy meals at a fast food restaurant. The happy meal typically consists of a hamburger, fries, coke and toy. No matter whether you choose different burgers/drinks, the construction of the kids meal follows the same process.

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 Builder Pattern

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

Allows for object level access control by acting as a pass through entity or a placeholder object.

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

The Builder provides an interface for creating the parts that make up a Product, and ConcreteBuilder provides an implementation of this interface.
The ConcreteBuilder keep track of the representation it creates, provides a way to get the result (Product) as well as constructing the product.
The Director constructs the object through the Builder’s interface. The Product is the object, usually complex, that we are constructing. This would include all the classes that define what we are constructing.

The builder pattern will typically use other creational patterns to get products built (e.g. Prototype or Singleton) and will often build a composite.

Would I Use This Pattern?

This pattern is used when object creation algorithms should be decoupled from the system, and multiple representations of creation algorithms are required. This decoupling is useful as you can add new creation functionality to your system without affecting the core code. You also get control over the creation process at runtime with this approach.

An example of the pattern in the Java API would the StringBuilder append method.

So How Does It Work In Java?

We’ll continue with our meals example from earlier.
First, we have the concept of a meal builder, that puts together the parts : main, drink and dessert. The Meal is the composite product that holds all the relevant parts.

// Builder
       public abstract class MealBuilder {
	protected Meal meal = new Meal();
	public abstract void buildDrink();
	public abstract void buildMain();
	public abstract void buildDessert();
	public abstract Meal getMeal();
}

Next we create two specific builders, one for kids, one for adults:

public class KidsMealBuilder extends MealBuilder {
	public void buildDrink() {
		// add drinks to the meal
	}
	public void buildMain() {
		// add main part of the meal
	}
	public void buildDessert() {
		// add dessert part to the meal
	}
	public Meal getMeal() {
		return meal;
	}
}

public class AdultMealBuilder extends MealBuilder {
public void buildDrink() {
		// add drinks to the meal
	}
	public void buildMain() {
		// add main part of the meal
	}
	public void buildDessert() {
		// add dessert part to the meal
	}
	public Meal getMeal() {
		return meal;
	}
}

In order to kick off the build process, we have a director:

// Director
public class MealDirector {
	public Meal createMeal(MealBuilder builder) {
		builder.buildDrink();
		builder.buildMain();
		builder.buildDessert();
		return builder.getMeal();
	}
}

And finally we have a client to run all of this:

// Integration with overal application
public class Main {
	public static void main(String[] args) {

		MealDirector director = new MealDirector();
		MealBuilder builder = null;

		if (isKid)
			builder = new KidsMealBuilder();
		} else
		{
			builder = new AdultMealBuilder();
		}
		Meal meal = director.createMeal(mealBuilder);
	}
}

Watch Out for the Downsides

There’s not many downsides that I see to the builder. The decoupling is useful, but the switch statements necessary when using the pattern on it’s own aren’t very appealing. As with all patterns, it adds complexity when used in the wrong places.

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 State Pattern

Today’s pattern is the State pattern, which allows objects to behave in different ways depending on internal state. State is used when you need a class to behave differently, such as performing slightly different computations, based on some arguments passed through to the class.

State in the Real World

Vending machines maintain an internal state which allow it to change it’s behaviour accordingly. For example, if there is no change available, it will demand exact change. When something is out of stock, it will deliver none of that product.

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 State Pattern

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

Allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.

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

The Context can have a number of internal States, whenever the request() method is called on the Context, the message is delegated to the State to handle. The State interface defines a common interface for all concrete states, encapsulating all behaviour associated with a particular state. The ConcreteState implements it’s own implementation for the request. When a Context changes state, what really happens is that we have a different ConcreteState associated with it.

This is all quite similar to the Strategy pattern, except the changes happen at runtime rather than the client deciding. State saves you from lots of conditional code in your Context: by changing the ConcreteState object used, you can change the behaviour of the context.

Would I Use This Pattern?

You should use the State pattern when the behaviour of an object should be influenced by it’s state, and when complex conditions tie object behaviour to it’s state.

So How Does It Work In Java?

We’ll use the state of an mp3 player to give an example of the state pattern in action. First we set up a context for our mp3 player.

//Context
public class MP3PlayerContext
{
	private State state;

	private MP3PlayerContext(State state)
	{
	   this.state= state;
	}
	public void play()
	{
		state.pressPlay(this);
	}

	public void setState(State state)
	{
		this.state = state;
	}

	public State getState()
	{
		return state;
	}

}

Now we’ll create our state interface. In this example, we’ve just got a play button.

private interface State
{
	public void pressPlay(MP3PlayerContext context);
}

And finally, creating a state for Standby and for Playing.

public class StandbyState implements State
{
	public void pressPlay(MP3PlayerContext context)
	{
		context.setState(new PlayingState());
	}

}

public class PlayingState implements State
{
	public void pressPlay(MP3PlayerContext context)
	{
		context.setState(new StandbyState());
	}

}

So this shows how the state pattern works at a simple level. Of course, our pressPlay methods would do more than simply set the state of the context.

Watch Out for the Downsides

There are some potential bad uses of the state pattern. For example, some operations may not be possible when the context is in certain states. This article proposes a nice solution to the problem

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 Flyweight Pattern

Today’s pattern is the Flyweight pattern, used to share large number of objects in an efficient way.

Flyweight in the Real World

The classic example of the Flyweight pattern is the representation of a character in a word processor. Rather than each character having seperate glyph objects that represent the font and formatting data, each character could have a reference to a flyweight glyph object shared by every instance of the same cahracter in the document. In this case, the character need only store it’s position in the the document, rather than it’s entire formatting information.

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 Flyweight Pattern

Flyweight is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Flyweight provided in the original Gang of Four book on Design Patterns states:

Facilitates the reuse of many fine grained objects, making the utilization of large numbers of objects more efficient.

When considering this pattern, you will need to think about intrinsic and extrinsic data. Intrinsic data is the data that makes this object instance unique. Meanwhile, extrinsic data is information that can be passed in through arguments. So, if you can make some data extrinsic for cases that you have a large number of objects, the Flyweight pattern may be exactly what you are looking for.

The Flyweight interface declares methods which flyweight instances can receive and use extrinsic data. TheFlyweightFactory is responsible for the creation and management of the flyweights, ensuring that they are shared properly. If the desired Flyweight isn’t created yet it will create and return one. Otherwise, it will return one from the current pool of flyweights.

ConcreteFlyweight adds capabilities for intrinsic state. This flyweight object must be sharable. TheUnsharedConcreteFlyweight provides a way to use this pattern without enforcing the shared concept the the interface encourages. However, most uses of this pattern involve sharable flyweights.

Would I Use This Pattern?

This pattern should be used when:

  • Many similar objects are used and the storage cost is high
  • The majority of each object’s state data can be made extrinsic
  • A few shared objects would easily replace many unshared objects
  • The identity of each object does not matter

The typical case for this pattern is with system resources, as mentioned in our real world example. Icons or folders are good candidates for use of this pattern.

So How Does It Work In Java?

Let’s use drawing lines of different colors as an example here. We want to avoid creating a new line for each color, instead choosing to reuse lines with the same color.

First, we’ll create an interface for our flyweights. The draw method provides the extrinsic data of where to draw the line

//Flyweight
public interface LineFlyweight
{
	public Color getColor();
	public void draw(Point location);
}

The line will implement this interface:

//ConcreteFlyweight
public class Line implements LineFlyweight
{
	private Color color; 

	public Line(Color c)
	{
		color = c;
	}

	public Color getColor()
	{
		return color;
	}

	public void draw(Point location)
	{
		//draw the character on screen
	}

}

Our factory will manage the creation of the line objects:

//Flyweight factory
public class LineFlyweightFactory
{
	private List<LineFlyweight> pool; 

	public LineFlyweightFactory()
	{
		pool = new ArrayList<LineFlyweight>();
	}

	public LineFlyweight getLine(Color c)
	{
		//check if we've already created a line with this color
		for(LineFlyweight line: pool)
		{
			if(line.getColor().equals(c))
			{
				return line;
			}
		}
		//if not, create one and save it to the pool
		LineFlyweight line = new Line(c);
		pool.add(line);
		return line;
	}

}

When the client wants to create a line, they can just use the factory as follows:

LineFlyweightFactory factory = new LineFlyweightFactory();
....
LineFlyweight line = factory.getLine(Color.RED);
LineFlyweight line2 = factory.getLine(Color.RED); 

//can use the lines independently
line.draw(new Point(100, 100));
line2.draw(new Point(200, 100));

Watch Out for the Downsides

One of the drawbacks of this pattern is that all instances of the class are related, so single instances of the class will not be able to behave independently from other instances.

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 Composite Pattern

Today’s pattern is the Composite pattern, which comes into play when developing a system where a component could either be an individual object or a representation of a collection of objects.

Composite in the Real World

In programming, composites are used when dealing with tree structures. This itself is quite an abstract concept. One example of composite that you see daily is a menu system, where a menu bar has menu has many menu items, which themselves can have submenus. Anything that can be modelled as a tree structure can be considered an example of Composite, such as an organization chart.

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 Composite Pattern

The Composite is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Composite provided in the original Gang of Four book on Design Patterns states:

Allow you to compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.

In it’s simplest form, we can think of a composite as a collection of objects, where any one of these objects could itself be a composite, or a simple object. Let’s take a look at the diagram definition before we go into more detail.

The Component interface defines the interface that all objects in the composed system need to use, whether they are leafs (simple objects) or compositions. However, this is usually implemented as an abstract class providing some default behaviour for the add, remove and getChild methods.

The Leaf has no children, and as such only needs to implement the operation method. The Composite needs to do more, as it also contains components. The composite will more than likely need to implement the operation method, which is considered as a Leaf-related operation. Sometimes this may not make sense for a composite to implement.  Usually, the Composite will implement methods by delegating to the children. The Client simply uses the Component  interface to manipulate the objects.

Would I Use This Pattern?

This pattern should be used when you want to represent objects in a hierachical fashion, or you need objects and composites to be treated uniformly.

Graphics frameworks are the most common use of this pattern.  The base Graphic object provides the base class for all other graphic objects, such as Line, Rectangle, which provide their own implementations of the paint()/draw() method. The Composite pattern is frequently used for abstract syntax tree representations.

So How Does It Work In Java?

Graphics is a great example of how the Composite pattern works, so I’ll use that here. First, we create an general interface for our graphics object. The main thing is that we have a paint method.  Each graphic could be composed of other graphics too, so we’ll need to provide a way to contain these objects.

//Component interface
public interface Graphic
{
	public void add(Graphic g);
	public void remove(Graphic g);
	public Graphic get(int index);
	public void paint();
}

Next, we’ll implement this interface for CompositeGraphic objects. The key point to note here is that it’s paint method delegates the painting to children objects:

//Composite
public class CompositeGraphic implements Graphic
{
	private List<Graphic> children = new ArrayList<Graphic>();

	public void paint()
	{
		//run the paint operation for each child
		for(Graphic g: children)
		{
			g.paint();
		}
	}

	public void add(Graphic g)
	{
		children.add(g);
	}

	public void remove(Graphic g)
	{
		if(children.contains(g))
		{
			children.remove(g);
		}
	}

	public Graphic get(int index)
	{
		if(index < children.size())
		{
			return children.get(index);
		}
	}

}

The leaf, in this case SimpleGraphic, cannot contain other graphics, so it doesn’t need to implement the list operations. The most important this is that it provides a concrete implementation of the paint() method:

//Leaf
public class SimpleGraphic implements Graphic
{

	public void paint()
	{
		//run the paint operation
	}

	/**
	 * Because we have no children, these operations will do nothing
	 **/
	public void add(Graphic g)
	{
		//unsupported operation
	}

	public void remove(Graphic g)
	{
		//unsupported operation
	}

	public void get(int index)
	{
		//unsupported operation
	}
}

And finally, for the client, things couldn’t be easier. All they need to do is to know about the interface, and all the work is done for them:

//Client.
public class GraphicsClient
{
	/**
	 * Given a graphics context, client can just call paint, without worrying if this is a composite or leaf
	 **/
	public void paint(Graphics g)
	{
		g.paint();
	}
}

Watch Out for the Downsides

The Composite pattern does one thing really well, and that is that it allows you to treat both nodes and leafs in the same way. However, by providing this flexibility and transparency, you’re choosing a trade-off on the Single Responsibility principle.  This is not necessarily a bad thing, but it’s something that you should keep in mind.

Your system could also be overly general, and it can be difficult to find objects. Taking this into account, the pattern probably isn’t ideal to use as a data structure. In cases where the ordering of child nodes is important, you will need to add in extra functionality, perhaps utilizing the Iterator pattern.

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 Singleton Pattern

The next pattern in our series is the Singleton pattern. Singleton is probably the most infamous pattern, as it’s use causes a divide in the development community- some say it belongs, others say it’s against object-orientation.

Singletons in the Real World

In the real world singletons represent anything that is unique, so in theory, every person is a singleton. Putting things into a more concrete example, your house probably has just one central electical fuse box.

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 Singleton Pattern

Singleton 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 Singleton provided in the original Gang of Four book on Design Patterns states:

Ensure a class has only one instance and provide a global point of access to it.

Across all 23 design patterns, the diagram definition of the Singleton pattern is the simplest:

We just provide one point of access to create an instance of the Singleton class. The constructor is kept private, giving the getInstance() method the responsibility of providing access to the Singleton.

This sequence diagram shows how simple it is for a client to get an instance of the Singleton.

Where Would I Use This Pattern?

When you need to ensure there’s one instance of an object, available to a number of other classes, you may want to use the Singleton pattern. Singletons are used a lot where you need to provide a registry, or something like a thread pool. Logging is also another popular use of Singletons, providing one single access point to an applications log file.

So How Does It Work In Java?

This example will show how to put together the classic Singleton in Java, without thinking about the threading complications which we discuss later on in this article.

The Singleton class has some characteristics that we generally want to ensure two things:

  • We lazily load our singleton based on the first request for access to it.
  • There is no other way of instantiating our Singleton

Keeping this in mind, here is our Java representation of a Singleton.

public class Singleton
{
    private Singleton instance; 

    private Singleton()
   {
    }

   public static Singleton getInstance()
   {
       if(instance==null)
      {
          instance = new Singleton();
       }
      return instance;
   }

}

We maintain the lazy loading principle here by only creating the instance when it is null, which will always be on the first call. Additionally, because we use a private constructor, we can only create the Singleton by calling the getInstance() method.

For completeness, here is how a client can access the Singleton:

//access the singleton
Singleton singleton = Singleton.getInstance();
//use the singleton

As you can see, it’s fairly simple – but there are downsides.

Watch Out for the Downsides

As I mentioned at the beginning of this article, the Singleton is infamous in object oriented systems. A lot of the time the Singleton is used as a shortcut, so that the designer doesn’t need to think properly about object visibility. If you’re hacking in a Singleton so that there is global access to a resource, maybe it’s not the right thing to do. It might be better to work out how to pass the reference to that resource around properly.

Another important consideration is multi-threading. If two threads call the getInstance() method at the same time, you can end up with two singletons. Making the getInstance() method synchronised solves this issue, but then you have the performance cost – calling a synchronised version of getInstance() will be slower than the non-synchronized version.  However, maybe the best way around this is to sacrifice lazy-loading in the Singleton, ensuring there can only ever be on instance. A number of alternatives are listed here.

Google have even provided a Singleton Detector, to discourage their use in programs. The page “Why Singletons are Controversial” gives another good overview on the pitfalls around the pattern.

First, programs using global state are very difficult to test. …the singleton user and the singleton become inextricably coupled together. It is no longer possible to test the user without also testing the singleton.
…..

Second, programs that rely on global state hide their dependencies.

If you’ve been following this series you’ll notice that no other pattern has had so many downsides and cautionary notes. It’s true for all patterns that you need to carefully consider it’s applicability to your problem before using it. With Singleton, consider it twice as much.

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 Template Method Pattern

Today’s pattern is the Template Method pattern, which defines a stub for an algorithm, deferring some implementation steps to subclasses.

Template in the Real World

The Template Method pattern is used when two or more implementations of a similar algorithm exist. In the real world templates are used all the time: for architectural plans, and throughout the engineering domain. A template plan may be defined which is then built on with further variations. For example, a basic house plan can have many variations such as adding an extensions or using a different heating system.

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 Template Pattern

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

Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithms structure.

In practice, the Template Method pattern is quite simple – let’s look at a class diagram representation

The AbstractClass contains the templateMethod(), which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm, but is decoupled for the actual implementation of these methods. All operations used by this template method are made abstract, so their implementation is deferred to subclasses.

The ConcreteClass implements all the operations required by the templateMethod that were defined as abstract in the parent class. There can be many different ConcreteClasses.

The Template Method pattern makes use of the Hollywood Principle: Don’t call us, we’ll call you. The template method in the parent class controls the overall process, “calling” subclass methods when necessary. The Hollywood principle avoids low level components depending on high level components, and instead give these low level classes (ConcreteClass) a way of hooking into the parent class (AbstractClass).

When broken down, there are four different types of methods used in the parent class:

  • Concrete methods
    Standard complete methods that are useful to the subclasses. These methods are usually utiity methods.
  • Abstract methods
    Methods containing no implementation that must be implemented in subclasses.
  • Hook methods
    Methods containing a default implementation that may be overidden in some classes. Hook methods are intended to be overridden, concrete methods are not.
  • Template methods
    A method that calls any of the methods listed above in order to describe the algorithm without needing to implement the details.

When Would I Use This Pattern?

The Template Method pattern is used when

  • When behaviour of an algorithm can vary, you let subclasses implement the behaviour through overriding
  • You want to avoid code duplication, implementing variations of the algorithm in subclasses
  • You want to control the point that subclassing is allowed.

Template Method may not be an obvious choice in the beginning, but the usual sign that you should use the pattern is when you find that you have two almost identical classes working on some logic. At that stage, you should consider the power of the template method pattern to clean up your code.

As you can imagine, use of the Template Method is fairly common. You’ll find it used in the Arrays class uses it for sorting. JFrame uses update() as a template method, subclasses of the JFrame use paint(Graphics g) as their hook method.

So How Does It Work In Java?

For our Java example, we’ll use a cross compiler as an example. First, we’ll create a generic cross compiler base class, with it’s crossCompile() method being the glue for the whole algorithm to run.

public abstract class CrossCompiler
{

	public final void crossCompile()
	{
		collectSource();
		compileToTarget();
	}

	//Template methods
	protected abstract void collectSource();

	protected abstract void compileToTarget();
}

Next we’ll create two specific implementations of our cross compiler, for iPhone and for Android:

public class IPhoneCompiler extends CrossCompiler
{
	protected void collectSource()
	{
		//anything specific to this class
	}

	protected void compileToTarget()
	{
		//iphone specific compilation
	}

}

public class AndroidCompiler extends CrossCompiler
{
	protected void collectSource()
	{
		//anything specific to this class
	}

	protected void compileToTarget()
	{
		//android specific compilation
	}

}

To complete this example, here is how you would use your cross compilers

public class Client
{
	public static void main(String[] args)
	{
	   CrossCompiler iphone = new IPhoneCompiler();
	   iphone.crossCompile();

	   CrossCompiler android = new AndroidCompiler();
	   android.crossCompile();
	}

}

Watch Out for the Downsides

There are some downsides to the template method pattern. Firstly, your base classes tend to get cluttered up with a lot of seemingly unrelated code. Program flow is a little more difficult to follow – without the help of stepping through the code with a debugger. Alex Miller provides a detailed rundown of the reasons he hates the template method pattern in his blog.

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 Strategy Pattern

Having focussed on the two factory patterns over the last week, today we’ll take a look at the Strategy Pattern, a useful pattern in changing algorithm implementations at runtime, without causing tight coupling.

Strategy in the Real World

To explain the strategy in the real world, let’s take the example of a software developer. If language isn’t an issue I might ask a developer to write a piece of code for me to create a user interface. One developer’s chosen language is Java, so he’ll develop the UI with Swing. Meanwhile, the other developer decides to use C#. I don’t mind, I’ve left the details of how to write the UI to the developers, and both have applied their own strategy. At any stage, the developer chould change their strategy, choosing to use a different language if they feel it’s necessary. It’s all about dynamically changing behaviours.

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 Strategy Pattern

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

Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour

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

In the above diagram Context is composed of a Strategy. The context could be anything that would require changing behaviours – a class that provides sorting functionality perhaps. The Strategy is simply implemented as an interface, so that we can swap ConcreteStrategys in and out without effecting our Context.

Let’s take a look at how some client might put the Strategy pattern into action:

Use of the Context from the client may vary – your client could tell the Context which strategy it would like to use, or the Context could decide on behalf of the client.  In my opinion, it’s better to leave this decision to the Context, as it removes the type switch statements that we saw in our Factory patterns.

Where Would I Use This Pattern?

The Strategy pattern is to be used where you want to choose the algorithm to use at runtime. A good use of the Strategy pattern would be saving files in different formats, running various sorting algorithms, or file compression.

The Strategy pattern provides a way to define a family of algorithms, encapsulate each one as an object, and make them interchangeable.

So How Does It Work In Java?

Let’s use the example of a file compression tool – where we create either zip or rar files. First we’ll need a strategy:

//Strategy Interfacepublic interface CompressionStrategy{   public void compressFiles(ArrayList<File> files);}

And we’ll need to provide our two implementations, one for zip and one for rar

public class ZipCompressionStrategy implements CompressionStrategy{

   public void compressFiles(ArrayList<File> files)   {     //using ZIP approach   }

}
public class RarCompressionStrategy implements CompressionStrategy{

   public void compressFiles(ArrayList<File> files)   {     //using RAR approach   }

}

Our context will provide a way for the client to compress the files. Let’s say that there is a preferences setting in our application that sets which compression algorithm to use. We can change our strategy using the setCompressionStrategy method in the Context.

public class CompressionContext{   private CompressionStrategy strategy;   

   //this can be set at runtime by the application preferences   public void setCompressionStrategy(CompressionStrategy strategy)    {       this.strategy = strategy;     }

  //use the strategy   public void createArchive(ArrayList<File> files)    {        strategy.compressFiles(files);   }

}

It’s obvious that all the client has to do now is pass through the files to the CompressionContext

public class Client{

   public static void main(String[] args)   {      CompressionContext ctx = new CompressionContext();      //we could assume context is already set by preferences       ctx.setCompressionStrategy(new ZipCompressionStrategy());          //get a list of files     ...     ctx.createArchive(fileList);    

   }}

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 Iterator Pattern

Today’s pattern is the Iterator pattern which formalizes how we move through a collection of data in a particular class

Iterator in the Real World

MP3 player control is a good example of an iterator. The user doesn’t mind how to view their list of songs, once they get to see them somehow. In older mp3 players, this was done using simple forward and back buttons. With the iPod this changed to the wheel navigation concept. The iPhone moves this on further to use swipe movements. Nevertheless, the same idea is provided by all interfaces – a way to iterate through your music collection.

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 Iterator Pattern

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

Provides a way to access the elements of an aggregate object without exposing its underlying represenation.

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

The Aggregate defines an interface for the creation of the Iterator object. The ConcreteAggregate implements this interface, and returns an instance of the ConcreteIterator. The Iterator defines the interface for access and traversal of the elements, and the ConcreteIterator implements this interface while keeping track of the current position in the traversal of the Aggregate.

Using this pattern, you can build on the standard concept of iteration to define special iterators that only return specific elements in the data set.

Would I Use This Pattern?

This pattern is useful when you need access to elements in a set without access to the entire representation. When you need a uniform traversal interface, and multiple traversals may happen across elements, iterator is a good choice.

It also makes you code much more reasonable, getting rid of the typical for loop syntax across sections of your codebase.

So How Does It Work In Java?

Java provides an implementation of the Iterator pattern, which provides next() and hasNext() methods. Creation of the iterator in Java is typically done through a method named iterator() in the container class.
The following example shows use of an iterator with a list :

List<String> list = new ArrayList<String>();
//add strings 

Iterator it = list.iterator();
while(it.hasNext())
{
   String s = it.next();
}

Now let’s go to an example where we create the constructs ourselves, with a remote control example.
First we’ll create an iterator with the standard methods:

//Iterator interface
public interface ChannelIterator
{

	public boolean hasNext();

	public void next();

	public String currentItem();

}

Next we create the Aggregate interface, in this case a TV.

//Aggregate interface
public interface TV
{
	public Channel getIterator();
	//other TV methods
}

The concrete implementation of the aggregator has the capability to create the iterator

//Concrete Aggregator
public class ConcreteTV
{
	private ChannelIterator iterator;
	private List<String> channels; 

	public ConcreteTV()
	{
		iterator = new ConcreteChannelIterator(channels);
	}

	public ChannelIterator getIterator()
	{
		return iterator;
	}

}

Finally the iterator helps control how we navigate the data.

//Concrete Iterator
//Iterator interface
public interface ChannelIterator
{
	private List<String> channels; 

	private int currentPos = 0; 

	public ChannelIterator(List<String> channels)
	{
		this.channels = channels;
	}

	public boolean hasNext()
	{
		if(currentPos + 1 < channels.size())
		{
			return true;
		}
		return false;
	}

	public void next()
	{
		currentPos++;
	}

	public String currentItem()
	{
		return channels.get(currentPos);
	}

}

Of course this is a one-way remote control. We could implement back() and hasBack() methods to navigate backwards in our iterator.

Watch Out for the Downsides

I don’t see any disadvantages to this pattern. It’s simple, widely used and provides more readable code. However, you may disagree – if so, please let me know in the comments section.

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 Decorator Pattern

Today’s pattern is the Decorator pattern, which allows class behaviour to be extended dynamically at runtime.

Decorator in the Real World

The concept of a decorator is that it adds additional attributes to an object dynamically. A real world example of this would be a picture frame. The picture is our object, which has it’s own characteristics. For display purposes we add a frame to the picture, in order to decorate it. You’re probably already familiar with the concept of wrapper objects, and in essence, that is what a Decorator is.

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 Decorator Pattern

The Decorator is known as a structural pattern, as it’s used to form large object structures across many disparate objects. The definition of Decorator provided in the original Gang of Four book on Design Patterns states:

Allows for the dynamic wrapping of objects in order to modify their existing responsibilities and behaviours

Traditionally, you might consider subclassing to be the best way to approach this – but there will be cases that subclassing isn’t possible, or is impractical. This leads us to the Open/Closed Principle: classes should be open for extension, but closed for modification. This is a good principle to keep in mind, as it keeps your class stable, but leaves it open for extension if someone wants to add behaviour.

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

The Component defines the interface for objects that can have responsibilties added dynamically, and the ConcreteComponent is simply an implementation of this interface. The Decorator has a reference to a Component, and also conforms to the  Component interface.  This is the important thing to remember, as the Decorator is essentially wrapping the Component. The ConcreteDecorator just adds responsibilities to the original Component.

Would I Use This Pattern?

The Decorator pattern should be used when:

  • Object responsibilities and behaviours should be dynamically modifiable
  • Concrete implementations should be decoupled from responsibilities and behaviours

As mentioned in the previous section, this can be done by subclassing. But too much subclassing is definitely a bad thing. As you add more behaviours to a base class, you will soon find yourself dealing with maintenance nightmare, as a new class is created for each possible combination. While the decorator can cause it’s own issues, it does provide a better alternative to too much subclassing.

So How Does It Work In Java?

You’ll see decorators being used in Java I/O streams. Stream classes extend the base subclasses to add features to the stream classes.

In our example, we’ll use emails to illustrate the Decorator.

First we have an email interface, which has a getContents method:

public interface IEmail
{
   public String getContents();

}

And we’ll provide a concrete implementation for use:

//concrete component
public class Email implements IEmail
{
   private String content;

   public Email(String content)
   {
      this.content = content;
   }

   @Override
   public String getContents()
   {
      //general email stuff
      return content;

   }

}

Now we’ll create a decorator which will wrap the base email with extra functionality. We’ll model this as an abstract class, and maintain a reference to the base email.

public abstract class EmailDecorator implements IEmail
{
   //wrapped component
   IEmail originalEmail;

}

Let’s say that emails that leave the company internal server need to have a disclaimer added to the end. We can just add in a decorator to handle this:

//concrete decorator
public class ExternalEmailDecorator extends EmailDecorator
{
   private String content; 

   public ExternalEmailDecorator(IEmail basicEmail)
   {
      originalEmail = basicEmail;
   }

   @Override
   public String getContents()
   {

      //  secure original
      content = addDisclaimer(originalEmail.getContents());
      return content;
   }

   private String addDisclaimer(String message)
   {
      //append company disclaimer to message
      return  message + "\n Company Disclaimer";
   }

}

And if we wanted to create secure, encrypted messages, we could use another decorator:

//concrete decorator
public class SecureEmailDecorator extends EmailDecorator
{
   private String content; 

   public SecureEmailDecorator(IEmail basicEmail)
   {
      originalEmail = basicEmail;
   }

   @Override
   public String getContents()
   {

      //  secure original
      content = encrypt(originalEmail.getContents());
      return content;
   }

   private String encrypt(String message)
   {
      //encrypt the string
      return  encryptedMessage;
   }

}

So, if our email sending client detects this message is going outside the company, we can invoke the appropriate decorator before sending:

public class EmailSender
{

   public void sendEmail(IEmail email)
   {
      //read the email to-address, to see if it's going outside of the company
      //if so decorate it
      ExternalEmailDecorator external = new ExternalEmailDecorator(email);
      external.getContents();
      //send 

   }
}

Watch Out for the Downsides

Overuse of the Open/Closed principle can lead to abstract and complex code. This principle should really only be used in places where code is least likely to change.

The Design Patterns book does point out a couple of disadvantages with this pattern. Decorators can lead to a system with a lot of smaller objects that will look similar to a developer and introduce a maintenance headache. Also, the Decorator and it’s enclosed components are not identical, so tests for object type (instanceof) will fail.

Find Out More


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