Decorator

 
Purpose The intent is to attach a responsibility to an object at runtime. Decoratoration is a flexible alternative to extending a class.

Sometimes we want to add a responsibility to an object A, not its whole class. This can be done by wrapping A in another object that adds the responsibility. The decorator (aka wrapper) implements A's interface. So, A's clients interact with decorated A as though it were A. The decorator uses A to implement A's functionality, but may perform additional actions before or after invoking A's methods. Transparency enables one to decorate the decorated object, etc., adding many responsibilities.

This may be handy, for example, when users can turn on/off an object's attributes via a checkbox (e.g., insert/delete a boundary around a table).

It is not clear that decoration is superior to adding attributes to the original class, which, when null, are interpreted to mean that the attribute (e.g., a border) is absent.
Structure Decorator structure
Consequences
  • A decorated object has no knowledge of its wrapper. This coupling reduction may, at times, be advantageous.
  • Multiple decorations result in a chain of method invocations for each original method.
  • Complicates the concept of equals: Decorated objects generally do not equal an undecorated, but otherwise equal object B.
Implementation To keep decorators light-weight, state is associated with ConcreteComponent classes & ConcreteDecorator classes.
Sample Code
Related Patterns The Strategy pattern also can be used to encapsulate behavior dynamically. In this case, the object does have information about the varying responsibility. For example, one could encapsulate a table object's border strategy, perhaps setting it to either a null strategy (no border is rendered) or a non-null (e.g., n pixels wide) strategy (a border is rendered).