Java装饰者模式

1 什么是装饰者模式

装饰者模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰者来包裹真实的对象。

所以装饰者可以动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的方案。

2 装饰者模式组成结构

    抽象构件 (Component):给出抽象接口或抽象类,以规范准备接收附加功能的对象。
    具体构件 (ConcreteComponent):定义将要接收附加功能的类。
    抽象装饰 (Decorator):装饰者共同要实现的接口,也可以是抽象类。
    具体装饰 (ConcreteDecorator):持有一个 Component 对象,负责给构件对象“贴上”附加的功能。

3 装饰者模式 UML 图解

代码示例:

abstract class Coffe {
    public String coffeBean = "咖啡豆";

    public String getCoffeBean() {
        return coffeBean;
    }

    public abstract double getPrice();
}

class LatteCoffee extends Coffe {
    public LatteCoffee() {
        coffeBean = "Latte";
    }

    @Override
    public double getPrice() {
        return 31.05;
    }
}


abstract class Starbuk extends Coffe {
    @Override
    public abstract String getCoffeBean();
}

class VanillaLatte extends Starbuk {
    private Coffe coffe = null;

    public VanillaLatte(Coffe coffe) {
        this.coffe = coffe;
    }

    @Override
    public String getCoffeBean() {
        return "香草拿铁";
    }

    @Override
    public double getPrice() {
        return 3 + coffe.getPrice();
    }
}

public class CoffeShop {
    public static void main(String[] args) {
        Coffe myCoffee1 = new LatteCoffee();
        System.out.println(myCoffee1.getCoffeBean() + myCoffee1.getPrice());
        Coffe myCoffee2=new LatteCoffee();
        VanillaLatte xcnt=new VanillaLatte(myCoffee2);
        System.out.println(xcnt.getCoffeBean()+xcnt.getPrice());
    }
}

参考资料:

https://www.cnblogs.com/shenwen/p/10768332.html

https://blog.csdn.net/csdn15698845876/article/details/81544562

https://segmentfault.com/a/1190000016508992

https://my.oschina.net/liughDevelop/blog/2987320

装饰者模式与代理模式的区别

https://www.jianshu.com/p/c06a686dae39

Java的23种设计模式

https://www.cnblogs.com/pony1223/p/7608955.html

原文地址:https://www.cnblogs.com/majestyking/p/12431724.html