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)

Observer Pattern

Handles the relation between a Publisher and his subscribers (or Subject/observers or Observable/observers).

How
  • The Observer-interface: All observers must implement this interface: So they all have a Notify-method.
  • The observable base-class: Keeps track of all the observer-objects (reference to their Observer-interface)
  • Your observable class will inherit from the observable baseclass. This class will thus inherit the behaviour that manages and notifies the observers. When needed, you just call NotifyObservers().
  • Your observers will implement the Observer-interface, so their Notify-method can be called by the Observable class.
To pass the new data between the observable and the observers:
  1. Pass an object with all the data via the Notify-methods
  2. The observer gets the data via the properties of the observable-object
Observable calls Notify() on an interface => Loosely coupled.

Strategy pattern

  • Ducks fly and quack
  • Rubber ducks don't fly and quack
  • => Different fly and quack behaviour
Encapsulate what varies! => Fly and quackbehaviour.

How
  • Create duckbehaviour- and flybehaviour-interfaces (Program to interface)
  • Different implementation in the concrete behaviour classes.
  • Duck base-class with reference to FlyBehaviour- and QuackBehaviour-interface.
  • The concrete Duck-classes will then use the appropriate implementation of the behaviours. (Composition)