裝飾者模式動態地講責任附加到對象上,若要擴展功能,裝飾者提供了比繼承更有彈性的替代方案。 ide
例如咖啡里加糖加奶加巧克力等等裝飾。 this
原始對象大可能是抽象類 對象
----------------------------------------- 繼承
飲料類 ip
public abstract class Beverage {
String description= "Unknown Beverage";
public String getDescription(){
return this.description;
}
public abstract double cost();
} get
------------------------------------ io
調料類 class
public abstract class Condiment extends Beverage {
public abstract String getDescription();
}
---------------------------------------------- 擴展
濃縮咖啡 sso
public class Espresso extends Beverage{
public Espresso(){
this.description="Espresso";
}
@Override
public double cost() {
return 1.99;
}
}
-------------------------------------
混合咖啡
public class HouseBlend extends Beverage {
public HouseBlend(){
this.description="House Blend Coffee";
}
@Override
public double cost() {
return 0.89;
}
}
----------------------------------
摩卡(巧克力)
public class Mocha extends Condiment {
private Beverage beverage;
public Mocha(Beverage beverage){
this.beverage=beverage;
}
@Override
public String getDescription() {
return beverage.getDescription()+", Mocha";
}
@Override
public double cost() {
return 0.2+beverage.cost();
}
}
-------------------------------------------
咖啡店
public class StarbuzzCoffee {---------------------------------------------
結果:
Espresso $1.99 House Blend Coffee $0.89 House Blend Coffee, Mocha $1.09