0

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!

4

1 回答 1

1

Milk、Whip 等类扩展了 CoffeeDecorator。该类在其构造函数中采用 Coffee 对象。查看ConcreteDecorator 类中getCost 的实现。它只调用装饰类中的 getCost 操作。

因此,当您具有如下层次结构时:

c = new Whip(new Sprinkles(new Milk(c)))

并运行:

c.getCost();

操作顺序是这样的:

The Whip instance runs the super.getCost() - in fact calling sprinkles.getCost()
The sprinkles.getCost() runs **its** super.getCost() - in fact calling Milk.getCost()
...
The coffee object returns 1
...
The sprinkles object adds its cost to that
The whip object adds its cost to the result.
于 2013-10-08T16:46:31.603 回答