5 java oop polymorphism inheritance design-patterns
我读了一个Decorator设计模式的例子.我知道这种设计模式动态地修改了一个特定实例的行为.我在下面给出的例子也是可以理解的.我不明白的一点是,当我调用c.getCost()牛奶对象时,它返回1.5.只有Simplecoffee的getCost()回报1,但是从哪里呢c.getCost奶回报1.5吗?
任何人都可以解释Milk类和Simplecoffee类之间的链接,以及getCost()在使用milk对象调用时如何执行方法流?该getCost()方法如何返回1.5?
//Decorator Design Pattern
interface Coffee {
public double getCost();
public String getIngredients();
}
class Simplecoffee implements Coffee {
public double getCost() {
return 1;
}
public String getIngredients() {
return "Coffee";
}
}
abstract class CoffeeDecorator implements Coffee {
protected Coffee decoratedcoffee;
protected String ingredientseparator = ":";
public CoffeeDecorator(Coffee decoratedcoffee) {
this.decoratedcoffee = decoratedcoffee;
}
public double getCost() {
return decoratedcoffee.getCost();
}
public String getIngredients() {
return decoratedcoffee.getIngredients();
}
}
class Milk extends CoffeeDecorator {
public Milk(Coffee decoratedcoffee) {
super(decoratedcoffee);
System.out.println("Milk Constructor");
}
public double getCost() {
return super.getCost() + 0.5;
}
public String getIngredients() {
return super.getIngredients() + ingredientseparator + "milk";
}
}
public class Decorator {
public static void main(String[] ar) {
System.out.println("calling simplecoffee in main");
Coffee c = new Simplecoffee();
System.out.println("Cost:" + c.getCost());
c = new Milk(c);
System.out.println("Cost:" + c.getCost());
}
}
Run Code Online (Sandbox Code Playgroud)
getCost()方法如何返回1.5?
该getCost()方法Milk首先调用引用的getCost方法.因此,这将调用返回1 的方法(读取:运行时多态性).接下来,该方法添加此调用的返回值(即1),从而将结果作为decoratedcoffeeSimpleCoffeegetCostSimpleCoffeegetCostMilk0.51.5
这是Decorator模式的重点.的装饰被用于通过缠绕一个新对象到现有的链产生的方法调用的链.