我正在尝试用装饰模式制作披萨(跟我一起):
假设我有以下内容:
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";
}
}
问题是我可以有重复的装饰器。
如何更改此代码的结构以添加"唯一性"约束 - 也就是说,每个Decorator最多只出现一次? (我的披萨店不允许顾客买双香肠,抱歉!)
class PizzaMaker
{
public static void main (String[] args)
{
Pizza pizza = new SausageDecorator(new SausageDecorator(new OliveDecorator(new PlainPizza())));
System.out.println(pizza.makePizza());
}
}
产量:基础比萨+橄榄+香肠+香肠
答案 0 :(得分:1)
为了添加唯一约束,您可以定义名为interface
的{{1}},如:
UniqueTopping
并让你的装饰类,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
添加。
topping
只会返回getTopping()
中添加的topping
。
另外,您的addTopping()
应该实施PlainPizza
以返回空UniqueTopping
,如下所示:
topping