2014-11-03 41 views
3
 
public abstract class Beverage { 

    protected String Description; 

    public String getDescription(){ 
     return Description; 
    } 

    public abstract int cost(); 

} 

public class Espresso extends Beverage{ 

    public int cost(){ 
     return 2; 
    } 
    public Espresso(){ 
     Description = "Espresso"; 
    } 
} 


abstract class CondimentDecorator extends Beverage{ 

    public abstract String getDescription(); 


} 

public class Mocha extends CondimentDecorator{ 

    Beverage beverage; 
    public Mocha(Beverage beverage){ 
     this.beverage=beverage; 
    } 

    @Override 
    public String getDescription() { 
     return beverage.getDescription()+", Mocha "; 
    } 
    @Override 
    public int cost() { 
     return beverage.cost()+0.5; 
    } 

    public Beverage remove(Beverage b) { 
     return b; 
    } 

} 
... 

有更多的像牛奶一样..大豆..等,并像HouseBlend咖啡..等装饰..如何从对象中移除装饰器?

,如果我有对象的摩卡牛奶装饰,我想只删除“摩卡”装饰。

Beverage beverage = new Mocha(new Espresso()); 
beverage = new Milk(beverage); 

编辑: 的情况是

  1. 客户已将快报与摩卡咖啡和牛奶。

  2. 现在Expresso装饰摩卡和牛奶。

  3. 突然客户想用鞭子取代摩卡。

+0

我理解它可能只是一个例子,有想法,但在特定的设置,我可能不会使用一个装饰,而是整合(例如,使用enum类),因为无论装饰器的顺序如何(例如,Milk&Mocha与Mocha&Milk相同),您可能都希望保持Description的一致性。 – didierc 2014-11-03 12:44:56

回答

1

你必须为提供者自己的逻辑,像:

CondimentDecorator#removeCondiment(Class <? extends CondimentDecorator>) 

有一个方法检查它是否是包装类的CondimentDecorator,并直接引用包裹饮料,绕过要删除的装饰器。在包装饮料上递归调用包装装饰器不匹配。

1

没有编写自定义装饰器来处理这个问题,你不能。除删除装饰的,你可以只重新饮料减去Mocha装饰

beverage = new Milk(new Espresso());