1
我試圖做一些披薩使用修飾模式(包涵):添加「唯一性」約束裝飾模式在Java中
假設我有以下幾點:
interface Pizza {
public String makePizza();
}
class PlainPizza implements Pizza {
@Override
public String makePizza() {
return "Base Pizza";
}
}
然後我有一個大致的裝飾:
abstract class PizzaDecorator implements Pizza {
protected Pizza specialPizza;
public PizzaDecorator(Pizza specialPizza) {
this.specialPizza = specialPizza;
}
public String makePizza() {
return specialPizza.makePizza();
}
}
而且裝飾的兩種實現方式:
class SausageDecorator extends PizzaDecorator {
public SausageDecorator(Pizza specialPizza) {
super(specialPizza);
}
public String makePizza() {
return specialPizza.makePizza() + addSausage();
}
private String addSausage() {
return " + sausage";
}
}
class OliveDecorator extends PizzaDecorator {
public OliveDecorator(Pizza specialPizza) {
super(specialPizza);
}
public String makePizza() {
return specialPizza.makePizza() + addOlives();
}
private String addOlives() {
return " + olives";
}
}
問題是我能夠重複裝飾器。
如何更改此代碼的結構以添加「唯一性」約束 - 也就是說,每個裝飾器最多可以顯示一次? (我的披薩店沒有讓客戶得到雙重香腸,對不起!)
class PizzaMaker
{
public static void main (String[] args)
{
Pizza pizza = new SausageDecorator(new SausageDecorator(new OliveDecorator(new PlainPizza())));
System.out.println(pizza.makePizza());
}
}
輸出:基本比薩+橄欖+香腸+香腸
我只是想學習Decorator模式。 – frozen