私はデコレータデザインパターンの一例を読みました。私は、このデザインパターンがある特定のインスタンスの動作を動的に変更することを理解しました。私が下に示した例もまた理解できる。私が理解していなかった点は、乳製品にc.getCost()
と呼ぶと、1.5を返します。 唯一Simplecoffee
のgetCost()
は1を返しますが、どこからc.getCost
のミルクリターン1.5ですか?Decoratorパターンチェーンメソッドはどのように呼び出されますか?
Milk
クラスとSimplecoffee
クラスの間のリンクを説明してください。ミルクオブジェクトで呼び出されたときにメソッドgetCost()
の実行がどのように流れますか? getCost()
メソッドは1.5をどのように返しますか? 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());
}
}
あなたは見つけるためにSimplecoffee' 'の' getCost'方法で 'Thread.dumpStackを()'を挿入できます。 –
基本的には、c = new Milk(c)と言ったときに、SimpleCoffeeインスタンスをフィールド(Interface Coffee経由で参照される)として設定し、decorcoffee.getCost();を呼び出して継承を呼び出しているCoffeeDecoratorコンストラクタです。継承を継承して1を返し、0.5を追加する親メソッドです。 – drgPP
「ミルクオブジェクトで呼び出されたときにメソッドがどのように流れるか」LOL – Reg