作者:Dfsk刘海_368 | 来源:互联网 | 2023-10-10 18:50
装饰者模式在不修改任何底层代码的情况下,给你的(或别人的)对象赋予新的职责。设计原则:类应该对扩展开放,对修改关闭。实体类***饮料**@authorNNroc*@date2
装饰者模式
在不修改任何底层代码的情况下,给你的(或别人的)对象赋予新的职责。
设计原则:
- 类应该对扩展开放,对修改关闭。
实体类
public abstract class Beverage {protected String description = "Unknown Beverage";public String getDescription() {return description;}public abstract double cost();
}
public abstract class CondimentDecorator extends Beverage {public abstract String getDescription();
}
实现类(咖啡种类 Beverage)
public class DarkRoast extends Beverage {public DarkRoast() {description = "Dark Roast Coffee";}public double cost() {return .99;}
}
public class Decat extends Beverage {public Decat() {description = "Decat Coffee";}public double cost() {return 1.05;}
}
public class Espresso extends Beverage {public Espresso() {description = "Espresso";}public double cost() {return 1.99;}
}
public class HouseBlend extends Beverage {public HouseBlend() {description = "House Blend Coffee";}public double cost() {return .89;}
}
实现类(配料 CondimentDecorator)
public class Mocha extends CondimentDecorator {Beverage beverage;public Mocha(Beverage beverage) {this.beverage = beverage;}public String getDescription() {return beverage.getDescription() + ", Mocha";}public double cost() {return .20 + beverage.cost();}
}
public class Soy extends CondimentDecorator {Beverage beverage;public Soy(Beverage beverage) {this.beverage = beverage;}public String getDescription() {return beverage.getDescription() + ", Soy";}public double cost() {return .15 + beverage.cost();}
}
public class Whip extends CondimentDecorator {Beverage beverage;public Whip(Beverage beverage) {this.beverage = beverage;}public String getDescription() {return beverage.getDescription() + ", Whip";}public double cost() {return .10 + beverage.cost();}
}
测试
public class StarbuzzCoffee {public static void main(String[] args) {Beverage beverage = new Espresso();System.out.println(beverage.getDescription() + " $" + beverage.cost());Beverage beverage2 = new DarkRoast();beverage2 = new Mocha(beverage2);beverage2 = new Mocha(beverage2);beverage2 = new Whip(beverage2);System.out.println(beverage2.getDescription() + " $" + beverage2.cost());Beverage beverage3 = new HouseBlend();beverage3 = new Soy(beverage3);beverage3 = new Mocha(beverage3);beverage3 = new Whip(beverage3);System.out.println(beverage3.getDescription() + " $" + beverage3.cost());}
}