装饰模式,通过其他子类运行的子类来获取行为?

时间:2013-10-02 05:11:51

标签: java design-patterns inheritance decorator aggregation

我一直在经历装饰​​模式,我对这个理论很了解,但是这只是一个轻微的技术部分,我无法理解。

我知道你可以添加装饰器,这样当你调用一个对象时,它也会调用所有装饰器函数,以便它们可以改变行为(例如向咖啡添加成分)。我不明白的是它的可能性。

Coffee c = new SimpleCoffee();

c = new Whip(new Sprinkles(new Milk(c)));
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());

这通过使用装饰器类添加了额外的成本和成分:Milk,Whip和Sprinkles。但是,这个单独的实现就像:

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";
    }
}

我没有看到他们互相引用的任何地方,他们只引用超级类,不管子类是咖啡装饰器,所以在上面的例子中c = new Whip(new Sprinkles(new Milk(c) ))),它如何获得所有额外的功能?

很难解释,但具体如何:

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

继承/聚合方面的工作?他们是否相互冲突?

完整的程序在维基百科上,我没有写任何使用过的例子,它们都可以在以下网址找到:

http://en.wikipedia.org/wiki/Decorator_pattern

感谢您的帮助!

1 个答案:

答案 0 :(得分: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.