Etymology Of Decorator Pattern

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

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.

5 Responses to “Etymology Of Decorator Pattern”

  1. Robert Cano Says:

    Very interesting post!
    I look forward to more!

  2. Digicorp » Blog Archive » Etymology Of Decorator Pattern Says:

    [...] Read More >> Tags: decorator pattern, OOPs Category: Code  |  Comment (RSS)  |  Trackback [...]

  3. Digicorp » Blog Archive » Decorator Pattern Explained Says:

    [...] 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 [...]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.