Etymology Of Decorator Pattern

Today our purpose is to know why and when to use decorator pattern. In last post about class explosion, we found that there is class explosion if we go with the first trial. Now what we can do to improve this design is, we can have one abstract super-class Food which will be specialised by Pizza and Sandwich classes. Food class will be abstract:

public abstract class Food {
private List ingredients;
private String description;
public abstract double cost();

Pizza class will extend this Food class and add pizza specific property in this class. For example, crustType, extraCheese, olives, jalapano, paneer etc. If the pizza subclass needs to add jalapano in the toppings, value of jalapano will be true. Similarly, we can have Sandwich class, extending Foot class and adding some Sandwich specific properties to it. Then we can have subclasses like ItalianPizza, DoubleCheesePizza, FreshVeggiePizza subclasses that extend Pizza and will have implementation of cost() method(by overriding). In this approach, we no more need to create separate classes for ItalianPizza with olives, with Paneer and so on. So we are getting rid of class explosion problem to some extent. Here is the class diagram for this.

Revised Class-diagram

Revised Class-diagram

Let’s check out how it works. When we create instance of, say ItalianPizza, then we can set jalapano, olives true or false according to what we want in the toppings of the pizza. Using the same properties we can calculate cost of the Pizza.

It’s now time to check out what issues can arise in this approach.
1. What if some new item is introduced for toppings? For example, corn. Leads us to modify the code – violation of open closed principle.
2. What if double cheese is required – lack of customisation at runtime. Need to add class for this. It could also be more olives (or triple cheese if it was me ).

The problem in the above lies in the compile-time binding of all the pizza ingredients with Pizza. What we really want is, the flexibility at run-time so that we can add or remove any behaviour or property to the object. Decorator pattern explained in the next post comes to the rescue.

Write a comment