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.

Getting To Grips With the Equinox Console

When developing Eclipse RCP applications, sometimes you’ll find that your plug-in’s capabilities don’t seem to available. The Equinox OSGi console is one of the most useful tools to inspect the state of all the plug-ins in a running application. This article gives a brief introduction to the console, and how it can be used to help with your development of an OSGi based system.

To make the console available, just use the -console parameter in your run configuration. If you want to see the console for an “installed” Eclipse instance, you can just add -console to the list of parameters for running Eclipse (e.g. eclipse.exe -console). Having done that you’ll see osgi> appear in the console output, similar to an MS-DOS window.

The following is a list of commands that can be used in the osgi console:

  • help
    Lists all available commands.

  • ss
    Provides a list of all the plug-ins and their current status. If you provide a string after ss, it will list all bundles containing that name. For example, if I used ss logging I would be presented with a list of plug-ins that contain logging in their name. ss here stands for short status.
  • start
    Starts up a plug-in. You can either pass through the full name of the plug-in to this command, or else you can use the symbolic id, as displayed from the previous ss command.
  • stop
    Stops a plug-in. Just like the start command, you can either pass through the full name of the plug-in or the symbolic id.
  • install
    Paired with a URL , this installs the plug-in that the URL refers to into your system. There is also an updatecommand, that allows you to update a plug-in using a URL.
  • uninstall
    This command takes the symbolic id of a plug-in and uninstalls it from your running system
  • diag
    Using the symbolic id, or the plug-in name, this command shows all resolution problems for a particular plug-in.

  • active
    Lists all the active plug-ins in the running system.

So when you have an issue with your plug-in:

  • Make sure it’s on the list of bundles, using the ss command. Or if you expect the plug-in to be running, use the activecommand.
  • Using the id of your plug-in (usually easier than typing in the full name) check that the status of your plug-in is  ACTIVE. If not maybe you need to force the plug-in to start up using the start command.

Once you become familiar with the OSGi console, it becomes a very powerful utility for investigating the overall status of your OSGi based application.

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

Today’s pattern is the Mediator pattern, used to handle complex communications between related objects, helping with decoupling of those objects.

Mediator in the Real World

An airport control tower is an excellent example of the mediator pattern. The tower looks after who can take off and land – all communications are done from the airplane to control tower, rather than having plane-to-plane communication. This idea of a central controller is one of the key aspects to the mediator 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 Mediator Pattern

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

Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other.  Allows for the actions of each object set to vary independently of one another.

The following diagram shows how the mediator pattern is modelled.

The Mediator defines the interface for communication between Colleague objects. The ConcreteMediator implements the Mediator interface and coordinates communication between Colleague objects. It is aware of all the Colleagues and their purpose with regards to inter communication. The ConcreteColleague communicates with other colleagues through the mediator.

Without this pattern, all of the Colleagues would know about each other, leading to high coupling. By having all colleagues communicate through one central point we have a decoupled system while maintaining control on the object’s interactions.

When Would I Use This Pattern?

The mediator is a good choice of pattern when the communication between objects is complicated, but well defined. When there are too many relationships between the objects in your code, it’s time to think of having such a central point of control.

An observer based variation of the mediator pattern is used in Java Message Service (JMS) implementations, which allows applications to subscribe and publish data to other applications. This is a common combination of patterns that makes sense.

So How Does It Work In Java?

Here we’ll use the Mediator pattern in the context of a chatroom application. First we’ll define an interface for our mediator

//Mediator interface
public interface Mediator
{
	public void send(String message, Colleague colleague);
}

While we described the Colleague as an interface above, it’s more useful to use an abstract class in this case:

//Colleage interface
public abstract Colleague
{
	private Mediator mediator;

	public Colleague(Mediator m)
	{
	    mediator = m;
	}

	//send a message via the mediator
        public void send(String message)
	{
	   mediator.send(message, this);
	}

	//get access to the mediator
	public Mediator getMediator()
	{
		return mediator;
	}

        public abstract void receive(String message);	

}

Now let’s create our concrete mediator implementation

public class ApplicationMediator implements Mediator
{
	private ArrayList<Colleague> colleagues;

        public ApplicationMediator()
        { colleagues = new ArrayList<Colleague>();} 

        public void addColleague(Colleague colleague)
        { colleagues.add(colleague);}

	public void send(String message, Colleague originator)
	{
		//let all other screens know that this screen has changed
		for(Colleague colleague: colleagues)
		{
			//don't tell ourselves
			if(colleague != originator)
			{
				colleage.receive(message);
			}
		}

	}

}

Finally we’ll create one concrete colleage.

public class ConcreteColleague extends Colleague
{
      public void receive(String message)
        {
           System.out.println("Colleague Received: " + message);
       }	

}

Here’s a client that drives the entire application:

public class Client
{
  public static void main(String[] args)
  {
      ApplicationMediator mediator = new ApplicationMediator(); 

     ConcreteColleague desktop = new ConcreteColleague(mediator)
     ConcreteColleague mobile = new MobileColleague(mediator)

      mediator.addColleague(desktop);
      mediator.addColleague(mobile);

      desktop.send("Hello World");
      mobile.send("Hello"); 

  }
}

Watch Out for the Downsides

While this pattern aims to reduce complexity, without proper design, the Mediator object itself can become very complicated itself.The Observer pattern could help here, with the colleague objects dealing with the events from the mediator, rather than having the mediator look after all orchestration.

Find Out More


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

Maintaining Your Value In the Software Industry

These days it can be tough to find the job you want as a software developer, either because the lack of opportunities out there, or facing huge competition in the process. In this article, I’d like to offer some tips that  might help you to maintain your value as a software developer.

All of these tips apply to those who are in current employment, or who are looking for a job. If you aren’t working right now, some of these points are essential: you don’t want it to appear as if you’ve lost interest in software when you’re not getting paid for it!

Challenge Yourself

While you may think that you know all that you need to know, there’s no harm in expanding your experience and improving your CV by achieving some relevant certification.

Certification is a really effective way of learning new things and refreshing on the things you already know.  Java developers have huge certification options available through the Sun Java Certification exams. Starting off with the SCJP exam, you can choose the path that suits you, all the way to Enterprise Architect. Eclipse developers can earn RCP and OSGi certification through the Eclipse Training Alliance.

Stay Educated

If certification isn’t an option for your technology, or you’ve done it all before, make sure that at the very least you stay educated. This can be as simple as buying a book, or doing an online tutorial. As well as keeping up to date on technologies that you use, it’s really rewarding to educate yourself in a new framework or technology. Once again, your CV gets a nice update and you’ll probably find ways to apply what you’ve learned in your current job.

Training course can be expensive, but if you can afford it – go for it. Make sure that you do a sufficient amount of research into the course to make sure it suits your needs and covers what you expect.

However,once you know the basics of software development, it’s easy to teach yourself.  There’s a lot of information available out there, and a large amount of the tools and IDEs that you need are probably free.

Join A Community

If you have a local user group, or gathering of other technologists, why not try to go to the meetings once in a while? Maybe start up a local technology conference and work on your presentation skills.

If you’re out of work right now, joining an open source project can be of huge benefit. You get to work as a team with other people passionate about technology, and pick up new skills from them. More importantly, joining an open source project can fill that empty year in your CV, and show that you’ve kept your skills sharp.

Find Your Voice

Finally, starting up your own blog can really help your confidence. It’s never been easier to set up a blog, with so many providers available. Teaching can be the best way of learning – so as you write about the technologies, tools and frameworks that interest you, you’ll find that you have an even better understanding. Researching new topics for your blog can be really interesting too. The most rewarding part is when you find that you have an audience and people are interested in what you have to say.

I should point out here that we do have an MVB program here at DZone, which is a really effective way of getting traffic to your blog from the DZone platform.

The key point I’d like to make is that you should never stand still as a software developer – there’s always someone behind you who will pass you out. Have you any other tips to share on staying sharp?