Design Patterns: Decorator

Hi guys, one more design pattern and today I am going to continue with a Structural Pattern. In particular, I will introduce you to Decorator design pattern. Sometimes this pattern is also known as Wrapper.

Decorator is a pattern that adds new features to an existing object without altering anything from the original object.

When do you have to use Decorator

  1. When we want to add functionalities in an object but not to an entire class dynamically and transparently.
  2. When we want to add functionalities that are not common to every object.
  3. When it doesn’t need to extend from a class because we don’t want to inherit a bunch of useless methods.

 

How to use it

Maybe the first way that comes to everyone’s mind in order to add new functions is through inheritance. The truth is that it is not the best option because you inherit a whole class that maybe you don’t need. You cannot control very well how and when you need a decorator.

Decorator offers a better solution to this problem. It gives us the ability to enclose an object that we want to add more functionalities to, to another object which is going to append the desire features. Decorator conforms to the interface of the object that we want to enhance.

Why Decorator Pattern?

I have already given you some very important reasons why you have to use this pattern and how. There is one more thing. This pattern is an excellent example of the open/closed principle.

The open/closed principle says an object must be open for extensions but closed for modifications.

Example

It is time to get an example. I am going to create a sword, it is a common sword and I want to decorate this sword with some magical powers. So, I am going to transform a common sword to an Excalibur sword.

I start with an interface named Sword.

Let’s implement this interface.

If we run this code and call attributes() method we get the following output.

Now let’s try to decorate this object with new features and giving it the magical power. I start with an abstract class named SwordDecorator that implements Sword interface.

As you can see this abstract class not only implements the Sword but has-a sword so as to append new actions in the desire object.
Let’s continue with ExcaliburSword that extends SwordDecorator.

 

So, this class takes as an argument a common sword and transforms it into an Excalibur sword by adding a magical power which is to blind its enemies and its power is increased from 1 which is a common sword to 10!

Let’s run this code

 

Output:

You can download the source code from GitHub.

Other useful resources:

code.tutsplus.com