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?

Why Do I Break The Rules? And Who Can Stop Me?

I’ve been developing software for quite a few years now and I notice that sometimes I break the rules, those best practices that I know are right to follow.  With so many blogs, books and articles covering the best way to develop software, the temptation to do your own thing still can take over – even when you know it’s wrong.

Ashamedly, I know that I’ve broken these rules in the past, as I’m sure most software developers have.

Test Driven Development

There’s no question in my mind that the best approach to developing any piece of code is to do tests first and then code. It focussed the developer in a different way than other approaches. You’ll find that you start a fresh project with good intentions and write your tests first. Then, as you get further along the way, you start to run out of time, so somethings got to give – it will usually be your tests.

There’s no excuse for this. All IDEs have JUnit built in to them and any developer with experience knows that it works. All developers who think that unit tests can be skipped should read Pragmatic Unit Testing. The authors put it best when they proclaim “unit testing means never having to say you’re sorry“.

Ignoring Broken Windows

Sticking with the Pragmatic Programmer series of books, one of the big lessons for software development is to have “no broken windows”. A broken window is a piece of badly written code that exists in your codebase. If the window isn’t fixed, then it will lead to other broken windows.

While I might not be the first one to pollute a codebase, I’m as guilty as that person for not fixing, or at least logging, the issue. I don’t know how many times I’ve gone through code, looking for where I need to add in my fix, and ignored rows of broken windows on the way.

Once again, there’s no excuse for this – I’m aware of the rule, I know that it makes sense, but I’m too caught up in getting my part done.

Mixed Up Spagetti Code

These days most of us declare the wonders of modular architectures – being able to seperate code down to bundles of responsibility and redeploy those bundles anywhere. So we create a bundle (or package) with UI responsibilities, and then we create another for logic. How many times have you seen that logic code starts to creep into your UI bundle? Of course this doesn’t become apparent until too late unless you’ve been following a test driven development approach, and have been testing anything that you can do on the UI through the logic layer.

Of everything on this list, this is the one that I hate the most, and as such is the one that I’m least prone to.

Diving Right Into The Code

It’s new project day, and you know you’re going to be using some cool technologies. Even if you’re using the same technology, at least it’s a clean slate. Nothing of the past three habits is going to get in the way this time. Or will it?

The tendency to avoid analysis, and dive straight into the code is common with all developers. It’s a natural thing as we like to get things running. It’s even excusable if you do a quick run through, take the lessons learned and then go through an analysis stage. But it’s the going back that’s the problem – once we’re in the code, we’re happy there.  Sometimes we sugarcoat this as an “agile approach” but is it really?

The Solution

The software industry would be in a much better state if we had a ready made solution to these bad habits. There’s a common theme through all of my failures above, and that is time. Doesn’t it look like I’m always up against the clock? Maybe that’s my fault for not giving clear enough estimates. But if I bump up an estimate to ensure I follow all these rules, am I just going to waste the extra time I’m given?

Of course there are things that can be done such as peer reviews, but nothing can beat good programmer discipline. Maybe we need to introduce some kind of hippocratic oath for software developers?

 

Deadlines Revealed: The Truth About How We Make It Across The Line

Even though all software developers have the best of intentions, sometime we have to bend the rules a bit in order to make deadlines. In most cases these hacks don’t last too long in the codebase, although Microsoft are just getting around to fixing a 17 year old bug. One of the funniest and most original articles I’ve read, that relates to this topic is Gamasutra’s Dirty Programming Tricks. The article is basically a collection of nine pieces of trickery and hackery that people encountered in their programming career. It would be great to hear of your own experiences in the Java development world.

It’s not all hacks though. My favourite trick in there is The Programming Antihero. In this example the team are working on a project where the memory footprint has to be low. Unknowingly to the team who working tirelessy to save every megabyte they can, a senior developer has purposefully injected a wasteful 2MB to make the problem seem worse. Once everyone has got as close as they can to the target, he deletes the call putting the project back on track.

“…so he explained to me that he had put aside those two megabytes of memory early in the development cycle. He knew from experience that it was always impossible to cut content down to memory budgets, and that many projects had come close to failing because of it. So now, as a regular practice, he always put aside a nice block of memory to free up when it’s really needed.”

You’ll find lots of other examples throughout the article covering some shameful hacks to get around those last minute bugs. In my time I’ve had to write plenty of “this is a hack”, or “here be monsters” comments, to warn other developers about the dirty code that I’ve had to inject into my applications. I’ve had to put in Thread.sleep() to get around some problems. I’ve seen times that adding a System.out.println() allows the code to execute nicely, where removing it has caused things to break.  Don’t worry, I’ve gone back and debugged through these issues carefully and fixed them.

At deadline time, sometimes you just have to do whatever it takes. I’d like to hear your software development confessions here. I’m sure there’s no developer out there that hasn’t damaged their integrity briefly to get across the line.

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.

Debugging Android: Using DDMS To Look Under The Hood

While working on an Android application recently, I ran into some problems, and was finding it difficult to work out what was actually going on in the emulator. As I’m using Appcelerator for my app development, I didn’t have the luxury of using the built in Eclipse tools to find out what was wrong. Luckily for me, Google have a tool for this type of situation: the Dalvik Debug Monitor.

You can invoke the debug monitor from the tools directory of your android SDK install using the ddms command.

Here’s a summary of what the tool provides:

Process View

When you first open DDMS, you will see a list of emulators on the left hand side. Each of these has a number of associated VMs running. Click on any of these VMs and you can view their information on the right hand side, including the threads and VM heap information. You can force garbage collection on any of the VMs at anytime using the trash can toolbar button.

You can also control the state of the emulator on the right hand side using the Emulator Control tab.  Here you can change items such as the voice and data telephony status. This is useful if you need to simulate roaming. You can even call your emulator, providing a source phone number. This section also has local controls to help you simulate location services, passing in you location using manual coordinates, GPX or KML.

File Explorer

The file explorer was the reason I booted up the debug monitor in the first place; I needed to see if a particular file I was providing with my app was included in the final apk that I sent to the device. Not only does the file explorer allow you to browse the emulator, but you can also push and pull files from the device, as well as deleting.  You can even create an SD card image for use in the emulator. When you’re confused about what’s getting included in your app, the file explorer is the place to go.

Device Log

The pane along the bottom presents you with the device log. Obviously this is really useful, particularly if you are not seeing enough information in your development tool.

Of course, the best way to get to know the tool is by using it. If you need to use the debug monitor, you will have your own specific use case, just as I did. I’m really impressed with the level of control and information in this tool. It’s already helped me out with some very tricky problems.