如何删除使用装饰器设计模式添加的项目?例如披萨点菜系统。我希望能够删除一些物品并降低价格。
public interface Pizza {
double getPrice();
}
public class SimplePizza implements Pizza {
@Override
public double getPrice() {
return 25;
}
}
public abstract class PizzaDecorator implements Pizza {
Pizza tempPizza;
public PizzaDecorator(Pizza a){
tempPizza = a;
}
@Override
public double getPrice(){
return tempPizza.getPrice();
}
}
public class Mushroom extends PizzaDecorator {
public Mushroom(Pizza newPizza){
super(newPizza);
}
public double getPrice(){
return tempPizza.getPrice() + 10;
}
}
答案 0 :(得分:0)
执行此操作的一种可能方法:
interface Pizza {
double getPrice();
public abstract Pizza removeItem();
}
class SimplePizza implements Pizza {
@Override
public double getPrice() {
return 25;
}
@Override
public Pizza removeItem(){
return null;
}
}
abstract class PizzaDecorator implements Pizza {
Pizza tempPizza;
public PizzaDecorator(Pizza a){
tempPizza = a;
}
@Override
public double getPrice(){
return tempPizza.getPrice();
}
public abstract Pizza removeItem();
}
class Mushroom extends PizzaDecorator {
public Mushroom(Pizza newPizza){
super(newPizza);
}
public double getPrice(){
return tempPizza.getPrice()+10;
}
@Override
public Pizza removeItem(){
return tempPizza;
}
}
class Onion extends PizzaDecorator {
public Onion(Pizza newPizza){
super(newPizza);
}
public double getPrice(){
return tempPizza.getPrice()+20;
}
@Override
public Pizza removeItem(){
return tempPizza;
}
}
public class Main{
public static void main(String args[]){
Pizza pizza = new SimplePizza();
// create new FarmHouse pizza
Pizza pizza2 = new Mushroom(pizza);
System.out.println(pizza2.getPrice());//Prints 35.0
pizza2 = new Onion(pizza2);
System.out.println(pizza2.getPrice());////Prints 55.0
pizza2 = pizza2.removeItem();
System.out.println(pizza2.getPrice());//Print 35.0
}
}