Thursday, May 3, 2012

Structural Patterns - 4.Decorator Pattern

If we want to add new behaviors to our object during runtime, we can choose Decorator Pattern. In this pattern, we define a class and some set of behaviors applicable to the class separately.

We can patch up the behaviors to the class dynamically with out altering the class implementation.

In other words, the object can be decorated dynamically with various behaviors as per the need. Here,both the decorator and the object to be decorated belong, to the same abstract type.

Consider an example of creating a rainbow. By default, rainbow is having a single color as its behavior. We can add or remove colors to/from the rainbow dynamically.Hence, the rainbow object can be constructed and the colors can be added/removed on the fly.

Rainbow is an implementation of the abstract type Colors. We implement separate decorators for each and every color so that both rainbow and all other decorators belong to the same type, Colors.

Following class diagram will explain the concept in detail,

Here, we can add any new decorator or repeat the existing decorator without altering the Rainbow code.

Based on the above diagram the following code snippet shows the decorator pattern in action,

  Colors rainbow = new Rainbow();
  rainbow = new IndigoDecorator(rainbow); //Decorator 1 (Indigo)
  rainbow = new VioletDecorator(rainbow); // Decorator 2 (Indigo)


Similarly, we can add dynamic behaviors to the rainbow object as,  

  rainbow=new AnyColorDecorator(rainbow);  //Decorator N (Any Color)

we can also, decorate the rainbow class with the same color, repeated for any number of times.


In the Java API, InputStreams, Readers,etc are having decorator implementations.

No comments:

Post a Comment