设计模式之装饰者模式

  • 在不同的饮品中加入调料,根据最后加入调料计算最后价格

  • 饮品基类

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());
    }
}
  • 对拓展开放,对修改关闭
  • 装饰者和被装饰者有相同的类型
  • 装饰者模式意味着一群装饰者类,这些类用来包装具体组件
  • 装饰者可以在被装饰者的行为前/后加上自己的行为,甚至将被装饰者的行为取代。

装饰者模式:动态地将责任附加到对象上,若要拓展功能,装饰者提供有别于继承的另一种选择。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值