Today our purpose is to know why decorator pattern. In last post, 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 specialized 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). By this approach, we no more need to create separate classes for ItalianPizza with olives, with Paneer etc. Here is the class diagram for this.

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 should we do if price of cheese goes up? Here, we are hard-coding price of cheese in cost() method.
2. What if some new item is introduced for toppings? For example, corn.
3. What if double cheese is required.
Oh god… save me now…
Its not going any where near how we want it to be. Next time, we will eliminate these all the issue by introducing one well-known decorator pattern.
June 3, 2009 at 4:42 am
Very interesting post!
I look forward to more!
June 3, 2009 at 8:07 am
Thanks for appreciation…
June 5, 2009 at 11:58 am
[...] Read More >> Tags: decorator pattern, OOPs Category: Code | Comment (RSS) | Trackback [...]
June 11, 2009 at 4:27 am
[...] Etymology Of Decorator Pattern [...]
June 15, 2009 at 7:58 am
[...] last post, we identified what issues can arise if we keep going with the design shown in Etymology Of Decorator Pattern. Lets take a quick look at what fundamental design problems exists in the design that we have [...]