Friday, October 30, 2015

Decorator

The Decorator attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Suppose we are working on a graphical interface and we want to add borders and scrollbars. One solution would be to inherit from the Window class and add the elements in the child class. By doing this excessively, we will end with an important number of specific-classes. To keep the code simpler, we may want to think about decroators :


The solution to this class of problems involves encapsulating the original object inside an abstract wrapper interface.

Widget* aWidget = new BorderDecorator(
new HorizontalScrollBarDecorator(
new VerticalScrollBarDecorator(
new Window( 80, 24 ))));
aWidget->draw();

Note that this pattern allows responsibilities to be added to an object, not methods to an object's interface. The interface presented to the client must remain constant as successive layers are specified.

For the piece of code to work, the correct representation of the Decorator is this one :

The decorator wraps the target object so that when we call OptionalOne.doThis(), it will call wrappee.doThis() (via super class here) and then add some decoration.

Check list

  1. Ensure the context is: a single core (or non-optional) component, several optional embellishments or wrappers, and an interface that is common to all.
  2. Create a "Lowest Common Denominator" interface that makes all classes interchangeable.
  3. Create a second level base class (Decorator) to support the optional wrapper classes.
  4. The Core class and Decorator class inherit from the LCD interface.
  5. The Decorator class declares a composition relationship to the LCD interface, and this data member is initialized in its constructor.
  6. The Decorator class delegates to the LCD object.
  7. Define a Decorator derived class for each optional embellishment.
  8. Decorator derived classes implement their wrapper functionality - and - delegate to the Decorator base class.
  9. The client configures the type and ordering of Core and Decorator objects.

0 comments:

Post a Comment