首页 > 其他 > 详细

设计模式10-装饰器模式

时间:2019-04-17 16:51:06      阅读:115      评论:0      收藏:0      [点我收藏+]
package DesignPattern;

public class DecoratorPattern {
    //来自Head First 设计模式
    //原始对象
    public static abstract class Beverage{
        String description="Unkown Beverage";
        public String getDescription(){
            return description;
        }
        public abstract double cost();
    }
    //关键在于装饰器本身也继承原料接口,装饰行为可以层层包装
    public static abstract class CondimentDecorator extends Beverage{
        public abstract String getDescription();
    }

    public static class Espresso extends Beverage{
        Espresso() {
            this.description="Espresson";
        }

        @Override
        public double cost() {
            return 1.99;
        }
    }
    public static class HouseBend extends Beverage{
        HouseBend() {
            this.description="House Blend Coffee";
        }

        @Override
        public double cost() {
            return 0.89;
        }
    }
    //抽象装饰器
    public static class Mocha extends CondimentDecorator{
        Beverage beverage;
        public Mocha(Beverage beverage){
            this.beverage=beverage;
        }
        @Override
        public String getDescription() {
            return beverage.getDescription()+",Mocha";
        }
        //装饰器功能增强方式,相当于把计算总价功能代理给装饰器模式
        @Override
        public double cost() {
            return .20+beverage.cost();
        }
    }

    public static void main(String[] args) {
        Beverage beverage = new Espresso();
        System.out.println(beverage.getDescription()+" cost:"+beverage.cost());
        Beverage beverage2 = new HouseBend();
        beverage2=new Mocha(beverage2);
        beverage2=new Mocha(beverage2);
        System.out.println(beverage2.getDescription()+" cost:"+beverage2.cost());
    }
}

设计模式10-装饰器模式

原文:https://www.cnblogs.com/zhouyu0-0/p/10724406.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!