java编程思想第4版第15章混型笔记及装饰器模式

来源:互联网 发布:日本历史书籍推荐知乎 编辑:程序博客网 时间:2024/06/07 05:41

一般使用接口来产生混型效果。

装饰器是使用组合和形式化结构,混型基于继承。

装饰器只是只是对由混型提出问题的一种局部解决方案。

动态的将责任链附加到对象上

咖啡-装饰器模式。

/** * Created by superdaojian on 17/3/7. */abstract class BasicCoffee {    public abstract double cost();}class Coffee1 extends BasicCoffee{    public double cost(){        return 3.14160;    }}class Coffee2 extends BasicCoffee{    public double cost(){        return 3.14159;    }}//调料基类,抽象装饰者abstract class CondimentDecorator extends BasicCoffee {    protected BasicCoffee basicCoffee;    public double cost(){        return 0;    }}class Milk extends CondimentDecorator{    public Milk(BasicCoffee basicCoffee) {        this.basicCoffee = basicCoffee;    }    public double cost() {        return basicCoffee.cost() + 0.2;    }}class Soy extends CondimentDecorator{    public Soy(BasicCoffee basicCoffee) {        this.basicCoffee = basicCoffee;    }    public double cost() {        return basicCoffee.cost() + 0.3;    }}class Sugar extends CondimentDecorator{    public Sugar(BasicCoffee basicCoffee) {        this.basicCoffee = basicCoffee;    }    public double cost() {        return basicCoffee.cost() + 0.4;    }}public class CoffeeTest{    public static void main(String[] args) {        //加milk的coffee1        BasicCoffee coffe1 = new Coffee1();        coffe1 = new Milk(coffe1);        System.out.println("milk coffee1 cost = " + coffe1.cost());        //加soy和sugar的coffee2        BasicCoffee coffe2 = new Coffee2();        coffe2 = new Soy(coffe2);        coffe2 = new Sugar(coffe2);        System.out.println("soy sugar coffee2 cost = " + coffe2.cost());    }}

若要扩展功能,装饰器提供了比继承更加富有弹性的代替方案。多用组合,少用继承。不用在程序还未运行时候创建大量类,而是在程序运行中按需动态组合类。扩展性好。如果还要根据咖啡的体积大小也要收取不同的费用,上面的代码不改,再编写继承CondimentDecorator的装饰者就可以了。当装饰者多了之后,那么程序中会有很多装饰者类,像上面我们就有了三个调料类,如果加上大杯小杯的要求之后,就有五个装饰者类。不过幸运的是这些类都很小,功能也比较单一。实际使用举例:JAVA IO流类以及Python中装饰器语法。

另外可以使用动态代理创建比装饰器更贴近混型的机制。




0 0
原创粉丝点击