zondag 7 maart 2010

Decorator pattern

To attach additional responsibilities to an object dynamically and thus extending it's functionality.

How
  • First here is your object base class for the objects you want to decorate. (e.g. Beverage)
  • Then the concrete classes for your objects. These all inherit from the base class, and add their own implementation to it. (e.g. Decaf, Espresso)
  • The decorator base class also inherits from the base class, AND it contains a variable of the base class type (Composition). (e.g. CondimentDecorator)
  • The concrete decorator classes inherit from the decorator base class and add their own implementation to it. (e.g. Milk, Mocka)
In code

//create an object of type Beverage
Beverage esp = new Espresso();
//Wrap it in a milk-object
Beverage milk = new Milk(esp);
return milk.Cost; //Calls the cost of the wrapped beverage-object + his own cost

(This pattern can be found in the Stream-classes)

Geen opmerkingen: