Thursday, November 12, 2015

Head First Design Pattern: CH3 Decorator Pattern

simple example is a coffee shop, you want to order coffee then add some topping like chocolate, milk and so on ...

the best way is to use the Decorator Pattern,
the solution looks like this:


1- you have the main interface Beverage, all drinks implements this interface (e.g. Espresso, Decaf ...) 
now all the Topping (e.g. Milk, Mocha, ...) also implement the Beverage interface but through the Decorator interface. as you can see the Docarator interface has an instance from Beverage (so you can use it to say add Topping on this Beverage).

the code looks like this:

1- the Beverage and Decorator:

as you can see here the CondimentDeocrator redifined getDescription() as abstract to force all the topping to override it.

2- The Drink classes
3- the Topping classes

as you can see the Topping (e.g Mocha) has a Beverage, and when you ask for the cost(), we will add the cost of Mocha to the Drink cost.

4- the Main

as you can see, we wrap the drink and topping together.

Java and Decorator
this behaviour is implemented everywhere in Java, specially in I/O

Undecorate
you may ask, what if i want to remove topping after adding it, well maybe Decorator is not the good pattern for that, think maybe about Chain of Responsibility for example.
however you can define this method in Topping classes 
public Beverage undecorate() {
          return this.beverage;
}
this method will returnthe actual drink without topping.

No comments:

Post a Comment