I am trying to make some pizza with the Decorator Pattern (bear with me):
Suppose I have the following:
interface Pizza {
public String makePizza();
}
class PlainPizza implements Pizza {
@Override
public String makePizza() {
return "Base Pizza";
}
}
And then I have a general decorator:
abstract class PizzaDecorator implements Pizza {
protected Pizza specialPizza;
public PizzaDecorator(Pizza specialPizza) {
this.specialPizza = specialPizza;
}
public String makePizza() {
return specialPizza.makePizza();
}
}
And two implementations of the decorator:
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";
}
}
The problem is that I am able to have duplicate decorators. How can I change the structure of this code to add a "uniqueness" constraint - that is, each Decorator can appear as most once?
class PizzaMaker
{
public static void main (String[] args)
{
Pizza pizza = new SausageDecorator(new SausageDecorator(new OliveDecorator(new PlainPizza())));
System.out.println(pizza.makePizza());
}
}
Output: Base Pizza + olives + sausage + sausage
Aucun commentaire:
Enregistrer un commentaire