装饰者模式

1、装饰者模式的动机

以客户端透明的方式以及,不需要创造更多子类的情况下,将对象的功能加以扩展,赋予类新的职责;

2、装饰者模式的定义

动态的将责任附加到新的对象上,若需要扩展功能时,装饰者提供了比继承更加具有弹性的替代方案;

3、装饰者模式的类结构图

image

模式分析:

4、优缺点和适用场景

优点:

缺点:

适用场景:

5、实例

例:饮料里面加入糖,奶等等其他作料;
饮料接口

/**
 * Desc:饮料的公共接口
 * ------------------------------------
 * Author:XXXX
 * Date:2017/9/1
 * Time:17:28
 */
public interface Beverage {
    String getDescription();

    Double getPrice();
}

装饰者接口

public interface Decorator extends Beverage {}

Coffee基础组件

/**
 * Desc:基础组件,原味Coffee
 * ------------------------------------
 * Author:XXXX
 * Date:2017/9/1
 * Time:17:36
 */
public class Coffee implements Beverage {

    public String getDescription() {
        return "coffee";
    }

    public Double getPrice() {
        return 9.0;
    }
}

糖装饰者

/**
 * Desc:糖装饰者
 * ------------------------------------
 * Author:XXXX
 * Date:2017/9/1
 * Time:17:40
 */
public class SugarDecorator implements Beverage {
    private Beverage beverage;

    public SugarDecorator(Beverage beverage) {
        this.beverage = beverage;
    }

    public String getDescription() {
        return beverage.getDescription()+"   加糖";
    }

    public Double getPrice() {
        return beverage.getPrice()+2.3;
    }
}

奶装饰者

/**
 * Desc:奶装饰者
 * ------------------------------------
 * Author:XXXX
 * Date:2017/9/1
 * Time:17:45
 */
public class MilkDecorator implements Decorator {
    private Beverage beverage;

    public MilkDecorator(Beverage beverage) {
        this.beverage = beverage;
    }

    public String getDescription() {
        return beverage.getDescription()+"  加奶";
    }

    public Double getPrice() {
        return beverage.getPrice()+3;
    }
}

测试类

/**
 * Desc:
 * ------------------------------------
 * Author:XXXX
 * Date:2017/9/1
 * Time:17:46
 */
public class Test {
    public static void main(String[] args) {
        Beverage coffee = new Coffee();
        //加糖Coffee
        Beverage coffee1 = new SugarDecorator(coffee);
        //即加糖,也加奶Coffee
        Beverage coffee2 = new MilkDecorator(coffee1);
        System.out.println(coffee2.getDescription());
        System.out.println("价格:" + coffee2.getPrice());
    }
}