Reputation: 185
I'm programming a coffee machine with many kinds of coffee. I offer normal coffee, espresso, cappuccino, but also Irish coffee (whiskey, coffee, sugar, whipped cream), Spanish Coffee (Cointreau, cognac, coffee, sugar, whipped cream) and Italian Coffee (Amaretto, coffee, sugar, whipped cream).
I'm planning to add more kinds of coffee in the future, that's why it needs to be easy to add more coffees without adding a class for each kind.
My solution would be to use the decorator pattern. However this will leave me with so many decorators like SugarDecorator
, MilkDecorator
, WhiskeyDecorator
, AmarettoDecorator
, WhippedCreamDecorator
...
How can I fix this without adding a decorator for each condiment?
Upvotes: 1
Views: 68
Reputation: 418
This is not a case for Decorator, looks like you wish to add optional ingredients. For this purpose you can use Builder as suggested by @user7294900.
Decorator pattern can be used when we wish to add a new functionality to an object while using earlier object as a raw material. In general why we need to be worried about added decorator classes (when required), as long as they provide required add-on functionality to existing object. Decorator classes do not add extra cost as they are optionally added at run time and are of pay-as-you-use type.
Upvotes: 0
Reputation: 58772
You can use Builder pattern to add more attributes to Coffee, e.g. add sugar and milk:
Coffee.builder().sugar(true).milk(true).build();
This way there's no extra classes, only attributes, but you need to build it on coffee creation
Builder Pattern makes it easy to construct an object which is extensible in independent directions at construction time, while the Decorator Pattern lets you add extensions to functionality to an object after construction time
Upvotes: 1