• 装饰者模式:动态的将新功能附加到对象上。在功能的扩展方面比继承更有弹性,装饰者模式也体现勒开闭原则(oop)

1、装饰者模式解决星巴克咖啡订单

  • image-20200509180110583

饮料抽象类

public abstract class Drink {
    public String description="";//饮料的具体描述
    private float price = 0.0f; //饮料的价格

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public abstract float cost();//计算价格抽象方法 具体价格具体类实现
}

Coffee类

public class Coffee extends Drink {

    @Override
    public float cost() {
        return super.getPrice();
    }
}

具体的咖啡:美式咖啡

public class LongBlack extends Coffee {
    public LongBlack() {
        setDescription("LongBlack");
        setPrice(12.0f);
    }
}

装饰者:这里是调味品

public class Decorator extends Drink {
    private Drink obj;

    public Decorator(Drink obj){//j通过聚合关系
        this.obj=obj;
    }

    @Override
    public float cost() {
        //自己的价格 加上被装饰者的价格
        return super.getPrice()+obj.cost();
    }

    @Override
    public String getDescription() {
        //装饰者的描述+装饰者的价格+被装饰者的描述
        return super.getDescription()+" "+super.getPrice()+" &&"+obj.getDescription();
    }
}

具体调料 巧克力 牛奶

public class Chocolate extends Decorator {

    public Chocolate(Drink obj) {
        super(obj);
        setDescription("巧克力");
        setPrice(2.0f);
    }
}

public class Milk extends  Decorator {

    public Milk(Drink obj) {
        super(obj);
        setDescription("milk");
        setPrice(1.5f);
    }
}

客户端使用

public class Client {
    public static void main(String[] args) {
        //点一份LongBlack
        Drink order = new LongBlack();
		//加一份巧克力
        order = new Chocolate(order);
        System.out.println("费用:" + order.cost());
        System.out.println("描述:" + order.getDescription());
        //加一份牛奶
        order = new Milk(order);
        System.out.println("费用:咖啡+巧克力+牛奶" + order.cost());
        System.out.println("描述:" + order.getDescription());

    }
}

2、jdk io源码

public class jdk {
    public static void main(String[] args) throws Exception {
        //InputStream 是抽象类 类似于Drink
        //FileInputStream是InputStream的子类,类似前面的Coffee
        //FilterInputStream是InputStream的子类, 类似于前面的Decorator 装饰者
        // DataInputStream是FilterInputStream的子类  具体的装饰者,类似前面的Milk
        DataInputStream dis = new DataInputStream(new FileInputStream("D://a.txt"));
        System.out.println(dis.read());
        dis.close();
    }
}