I've been going through the Decorator Pattern and I understand the theory pretty well, however theres just a slight technical part that I can't get my head around.
I understand that you can add decorators so that when you call an object, it calls all of the decorator functions as well so that they can change the behaviour (Such as adding ingredients to a Coffee). What I don't understand is how its possible.
Coffee c = new SimpleCoffee();
c = new Whip(new Sprinkles(new Milk(c)));
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
This adds the extra cost and ingredients to the functions by using the decorator classes: Milk, Whip and Sprinkles. However, this individual implementation is like:
class Milk extends CoffeeDecorator {
public Milk (Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.5;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Milk";
}
}
I don't see anywhere where they reference each other, they only reference the super class which regardless of the subclass would be the coffee decorator, so in the above example where c = new Whip(new Sprinkles(new Milk(c))), how does it receive all the extra functionality?
Its hard to explain, but how exactly does:
c = new Whip(new Sprinkles(new Milk(c)))
Work in terms of inheritance/aggregation? Do they run through each other?
The full program is at Wikipedia, I didn't write any of the examples used, they can all be found at:
http://en.wikipedia.org/wiki/Decorator_pattern
Thanks for all the help!