In 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 already discussed.
In the existing design, we have all the possible toppings of Pizza hard-coded into the Pizza class. Which are, in fact, individual Object in the real world. So in a way, they are Add-on objects that can be used to decorate our pizza. If we want to add new item as toppings, we need to modify the class. Ideally, we should be able to add any new topping “without modifying the class”, hence we come to know Open-closed principal.
“Classes should be closed for modification and open for enhancement.”
Now question is how to achieve this. Let’s note down what approach we need to follow to get maximum flexibility in design (maximum in terms of toppings and calculating its cost) in creating one FreshVeggiePizza with Paneer and Olives.
1. Take plain Pizza object.
2. Decorate it with Paneer.
3. Decorate it with Olives.
4. Call cost() method, which will be delegated to “Add-on” or “Decorator” objects also to add up their cost.