For those, skilled in Java development, Decorator patterns are nothing new, as they are quite common in Java, i.e. FileInputStream with it’s decorator BufferedInputStream class. The definition says:

The Decorator Pattern attaches additional responsibilities to an object dynamically.

More theoretical background can be found on Wikipedia.

I will base this example on the article Design Patterns – Part 1: Strategy pattern. For those that have not read the article, do so now, as it will make things easier to understand here. To summarize, we had three types of product: e-download, events and software, to which we added behavior.

Now, project manager thought it would be nice if we could sell our software in three different packages: Basic, Advanced and Pro. Each having different price.

Why use decorator pattern?

It can be done in multiple ways. However, using decorator pattern, we assure that no already working code will be altered and thus decrease possibility of inserting bugs into already operational code.

Problem implementation

We already have a class called Software that will represent a concrete component. What we have to do is create decorator and three classes for options. Also we do make a small change in Product class and add getDescription and getPrice methods. Code is below:

How to use this?

Simple code below, shows you how easy it is to use this set of classes to append different product options to a product.

This is all there is to decorator pattern. As you can see, it is easy to use and even simpler to implement.