2017-06-30 70 views
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()); 
     } 
    } 

輸出:基本比薩+橄欖+香腸+香腸

+1

我只是想學習Decorator模式。 – frozen

回答

1

爲了添加唯一約束,你可以定義一個名爲interfaceUniqueTopping

public interface UniqueTopping { 
    public String getTopping(); 
    public void addTopping(); 
} 

,有你的裝飾類,PlainPizza類實現它。

在你的裝飾類,有一個叫做topping一個私有變量和落實getTopping()addTopping()象下面這樣:

class SausageDecorator extends PizzaDecorator implements UniqueTopping { 

    private String topping = ""; 

    public SausageDecorator(Pizza specialPizza) { 
    super(specialPizza); 
    } 

    public String makePizza() { 
    addTopping(); 
    return specialPizza.makePizza() + " " + getTopping(); 
    } 

    @Override 
    public String getTopping() { 
    return topping; 
    } 

    @Override 
    public void addTopping() { 

    if (!specialPizza.getTopping().equals(getTopping())) { 
     topping = "sausage"; 
    } 

    } 

} 

請參閱addTopping()只增加如果在構造函數中傳遞的specialPizza有不同toppinggetTopping()只是返回addTopping()中添加的topping

而且你PlainPizza應該實現UniqueTopping返回象下面空topping

class PlainPizza implements Pizza, UniqueTopping { 
    @Override 
    public String makePizza() { 
    return "Base Pizza"; 
    } 

    @Override 
    public String getTopping() { 
    return ""; 
    } 

    @Override 
    public void addTopping() { 

    } 

}