samedi 22 avril 2017

Using Lists Instead of Decorator Pattern?

A Decorator Pattern use case from "Head First: Design Patterns" book made me have this question. I'll try to write it down:

It's a coffee shop system with some coffees and a lot of condiments you can put in them (for an extra cost), you need to be able to order and charge for a coffee with any condiments the costumer desires, and to avoid having total mayhem (e.g. booleans to keep track of the condiments) Decorator Pattern is used. We have an abstract Beverage class, each type of coffee as concrete components and each condiment as concrete decorators wrapping up a Beverage and calculating it's cost by delegation, like this:

Beverage Class Diagram

And so we have the following process returning a coffee cost:

Coffee Cost Delegation

My question is: Why not implement this with Lists instead of the Decorator? We could have a list of Condiment in each Beverage and calculate the cost by iterating through the List. To order a coffee we would just have to instantiate it once and add the desired condiments, avoiding declarations like:

// Using second image example
Beverage beverage = new DarkRoast(beverage);
beverage = new Mocha(beverage);
beverage = new Whip(beverage);

In addition to that we would have more flexibility for operations like giving discount for a coffee not including it's condiments, once we won't have decorators wrapping up the coffee. This is a matter that have been long studied, I know I'm missing something or maybe I got something wrong, so if you have any thoughts on this I would love to know and discuss it further.

Aucun commentaire:

Enregistrer un commentaire