设计模式-装饰者模式

  1. 定义
    装饰者模式动态地将责任责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

  2. 实现要点
    装饰器与被装饰的类需要继承自相同接口,来达到类型匹配。装饰器持有被装饰的类的实例。

  3. 代码实例

    /**
     * 基础组件
     */
    abstract class Beverage {
    
        private String description = "Unknown Beverage";
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        public abstract double cost();
    }
    
    /**
     * 装饰器基类
     */
    abstract class Decorator extends Beverage {
    
        @Override
        public abstract String getDescription();
    }
    
    /**
     * 被装饰的类
     */
    class Espresso extends Beverage {
    
        public Espresso() {
            setDescription("Espresso");
        }
    
        @Override
        public double cost() {
            return 1.99;
        }
    }
    
    /**
     * 装饰器
     */
    class Mocha extends Decorator {
    
        private Beverage beverage;
    
        public Mocha(Beverage beverage) {
            this.beverage = beverage;
        }
    
        @Override
        public double cost() {
            return beverage.cost() + 0.29;
        }
    
        @Override
        public String getDescription() {
            return beverage.getDescription() + ", Mocha";
        }
    }
    
    class CoffeeTest {
        public static void main(String[] args) {
            Beverage beverage = new Espresso();
            beverage = new Mocha(beverage);
    
            System.out.println(beverage.getDescription() + " " + beverage.cost());
        }
    }
    
posted @ 2019-08-15 17:50  bosslv  阅读(127)  评论(0编辑  收藏  举报