Pages

Wednesday, March 28, 2012

Design Pattern Tutorial Part 1: The Decorator Pattern (Structural Pattern)

The Decorator Pattern is used to extend the functionality of a particular object in runtime without changing the object hence without affecting the other instance of the same class. The object is said to be “decorated” with new extended functionality. This is achieved by creating a new wrapper or “decorator” class which wraps the original class. 

 

Features

One of the key features of the Decorator Pattern, from the point of implementation, is that a decorator class both inherits the original class and contains an instance of it. The other features are:
  • The original object remains unaffected by the decoration and so does the other instances.
  • No one class becomes burdened with lots of features making the objects light-weight.
  • The decorations are independent from each other, so that hundreds of decorators can be there to provide thousands of decoration combinations.

 

Uses

The Decorator pattern may be useful in following situations:
  • For evolving systems where there are frequent changes in functionality.
  • To attach new functionality or behaviour to an object.
  • To Change the behaviour of an object without affecting other instances.
  • Avoid subclassing as too many classes could result.
  • Where there is a component class unavailable for subclassing.

 

Design

 

  • IComponent: The interface that identifies the classes of objects that can be decorated.
  • Decorator: The class that both implements the “IComponent” interface and has an instance of it. It is possible to have more than one classes of this kind.
  • Component: The original class which can be decorated by extended behaviours.
  • DecoratorA & DecoratorB: Extended classes of “Decorator” for further extension.

No comments:

Post a Comment