Saturday, November 3, 2012

Decorator Design Pattern

Last post I discussed Strategy Design Pattern, continuing with the same topic, today I will write something about Decorator Design Pattern.

In case of Strategy, you encapsulate code in external algorithms for easy use rather than spreading it around inside your core code and modifying it throughout that code.

The Decorator takes a different approach. Instead of using external algorithms, this design pattern is all about using wrapper code to extend your core code.

The formal definition of the Decorator pattern from the GoF book (Design Patterns: Elements of Reusable Object-Oriented Software) says you can, “Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.”

Lets see how the example code looks like.

1.     First you define an interface class with a method operation() of type string.

2.     Next you define a class that implements this interface and method operation() returns “computer”.


3.     Now you define an abstract class that implements the interface you defined earlier. This class is actually a pass through class with a method new() having a parameter.


4.     Now you define two concrete classes that extend the abstract class you created in previous step. Notice the operation() methods.



5.     Finally you need a job to put all the pieces together.

6.     The infolog

This is what is happening. When you call the monitor’s operation() method, the following occurs in this order:

1. The monitor’s operation() method calls the disk wrapper’s operation() method.
2. The disk wrapper’s operation() method calls the computer object’s operation() method.
3. The computer object’s operation() method returns the text "You are getting a computer and a disk".
4. The monitor wrapper’s operation() object then adds "and a monitor" to give you the resulting final string, "You are getting a computer and a disk and a monitor".

Hope the post was clear and feel free to ask me for the xpo.

No comments:

Post a Comment