問題一覧に戻る
上級高度な機能
問題116: デコレーターパターン
デコレーターパターンを使用してオブジェクトに動的に機能を追加します。継承の柔軟な代替として、コンポジションを通じて動作を拡張する方法を学びます。
interface Coffee {
String getDescription();
double getCost();
}
class SimpleCoffee Coffee {
public String getDescription() { return "Coffee"; }
public double getCost() { return 2.0; }
}
// デコレーター基底クラス
abstract class CoffeeDecorator Coffee {
protected Coffee coffee;
public CoffeeDecorator(Coffee ) {
this.coffee = ;
}
}
// 具体的なデコレーター
class MilkDecorator extends {
public MilkDecorator(Coffee coffee) {
super(coffee);
}
public String getDescription() {
return coffee. + " + Milk";
}
public double getCost() {
return coffee. + 0.5;
}
}