Reputation: 2229
I'm watching a course about Design Patterns and the example they used for decorator pattern is the Pizza and Toppings example ( you can find the example here as well). Please have a look at the link to understand my issue
What I don't like about this pattern as mentioned in the comments of the link I added is that a topping is not a pizza so why should it inherit the pizza class?
The solution I have in my mind is using an array of PizzaDecorators
objects in a Pizza
object and use that array to add or remove toppings from a pizza.
Isn't this solution much simpler than using the decorator pattern? Why should we consider using the decorator pattern in a situation like this?
Upvotes: 0
Views: 72
Reputation: 17066
...a topping is not a pizza so why should it inherit the pizza class?
This comment was answered in the subsequent one: it's simply an issue of naming. Each topping should be named PizzaWithTopping.
...use an array to add or remove toppings from a pizza?
This solution makes a couple of assumptions.
Pizza
class? You might be making pizzas for a specific store, where the Pizza
is determined by a franchise. One way the franchise controls quality is by not allowing individual stores to edit the base Pizza
code.Pizza
object mutable? Mutability leads to bugs that immutability can avoid. This is a bigger architectural decision than just editing an array.Why should we consider using the decorator pattern in a situation like this?
The main advantage of the Decorator pattern over a "collection of enhancements" is that Decorator obeys the Open-Closed Principle. Decorator applies equally to any class, whether you own it or not, and whether the enhancements are foreseeable or not.
A collection requires that you either,
In a well-known and relatively small domain like Pizza, this might not be a serious problem. Maybe the toppings never become more complex than adding one-at-a-time through a single API. But with the Decorator, you're covered either way.
Upvotes: 1