Decorator Pattern - Multiple wrappers or quantity property?
I'm making use of the decorator pattern for one of t开发者_JS百科he first times, as part of a Uni project. As far as I can see, the pattern seems to be meant more for adding functionality in a modular manner, however we've been taught it with uses such as a coffee or pizza maker, where the object has modular components that are added - changing properties rather than behaviour.
I'm trying to make the most of both uses, however I've come up with a question. In the example in the book we're using (Head First Design Patterns), the pattern is used in a coffee shop creating different coffees. So, for example, milk, froth, sugar, sprinkles are all decorators.
How would you implement a system that used the same decorator multiple times (for example, a coffee with two sugars)? Would you rewrap the coffee, or give sugar a quantity property? Or (as i'm starting to suspect) would this never be an issue as the pattern isn't designed to be used this way?
The decorator doesn't care about how decorated the given object already is. Neither the decorator nor the given object stores any information about this. Essentially, you want to change the behaviour/state of the decorator, so this is to be done from inside the decorator.
So, give Sugar
a quantity
property. You could do this by adding a new constructor taking an extra argument (and let the standard constructor default the quantity
to 1
and document it accordingly).
精彩评论