在不同的饮品中加入调料,根据最后加入调料计算最后价格
饮品基类
public abstract class Beverage {
String description = "Unknown Beverage";
// 返回当前饮品的种类
public String getDescription() {
return description;
}
// 返回当前饮品的价格
public abstract double cost();
}
- 调料装饰者基类
//为了让Condiment Decorator(调料装饰者)能够取代Beverage,所以将它扩展至Beverage类
public abstract class CondimentDecorator extends Beverage{
public abstract String getDescription();
}
- 一种饮品
//一种饮料,继承至Beverage
public class Espresso extends Beverage{
public Espresso() {
description = "Espresso";
}
public double cost(){
return 1.99;
}
}
- 一种调料
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 .22 + beverage.cost(); //将被装饰者的价格加上当前价格
}
}
- 咖啡屋
public class CoffeeHouse {
public static void main(String[] args) {
Beverage beverage = new Espresso();
System.out.println("price of only espresso " + beverage.getDescription()+" : " + beverage.cost());
beverage = new Mocha(beverage);
System.out.println("price of espresso with Mocha" + beverage.getDescription()+" : "+ beverage.cost());
beverage = new Mocha(beverage);
System.out.println("price of espresso with Double Mocha" + beverage.getDescription()+" : "+ beverage.cost());
}
}
- 对拓展开放,对修改关闭
- 装饰者和被装饰者有相同的类型
- 装饰者模式意味着一群装饰者类,这些类用来包装具体组件
- 装饰者可以在被装饰者的行为前/后加上自己的行为,甚至将被装饰者的行为取代。
装饰者模式:动态地将责任附加到对象上,若要拓展功能,装饰者提供有别于继承的另一种选择。