7 decorator pattern

Decorator Pattern

First, application examples

Coffee Order Item

1) types of coffee / single coffee: Espresso (espresso), ShortBlack, LongBlack, Decaf

2) spices: Milk, Soy, Chocolate

3) requirements in the expansion of new types of coffee, good scalability, easy to change.

Second, the decorator pattern

Dynamic new features attached to the object. In terms of target function expansion is more flexible than inheritance

1. decorator pattern to solve the coffee order item

2. orders of the decorator pattern: in 2 parts chocolate milk and a LongBlack

3. code implementation

public class CoffeeBar {
    public static void main(String[] args) {
        // 装饰者模式下的订单:2份巧克力+一份牛奶的LongBlack
        // 1. 点一份 LongBlack
        Drink order = new LongBlack();
        System.out.println("费用1=" + order.cost());
        System.out.println("描述=" + order.getDes());

        // 2. order 加入一份牛奶
        order = new Milk(order);
        System.out.println("order 加入一份牛奶 费用 =" + order.cost());
        System.out.println("order 加入一份牛奶 描述 = " + order.getDes());

        // 3. order 加入一份巧克力
        order = new Chocolate(order);
        System.out.println("order 加入一份牛奶 加入一份巧克力  费用 =" + order.cost());
        System.out.println("order 加入一份牛奶 加入一份巧克力 描述 = " + order.getDes());

        // 4. order 加入一份巧克力
        order = new Chocolate(order);
        System.out.println("order 加入一份牛奶 加入2份巧克力   费用 =" + order.cost());
        System.out.println("order 加入一份牛奶 加入2份巧克力 描述 = " + order.getDes());
    }
}
public abstract class Drink {
    public String des; // 描述
    private float price = 0.0f;
    public String getDes() {
        return des;
    }
    public void setDes(String des) {
        this.des = des;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    
    //计算费用的抽象方法
    //子类来实现
    public abstract float cost();
}
public class Decorator extends Drink {
    private Drink obj;
    
    public Decorator(Drink obj) { //组合
        this.obj = obj;
    }
    @Override
    public float cost() {
        // getPrice 自己价格
        return super.getPrice() + obj.cost();
    }
    
    @Override
    public String getDes() {
        // obj.getDes() 输出被装饰者的信息
        return des + " " + getPrice() + " && " + obj.getDes();
    }
}
public class Coffee  extends Drink {
    @Override
    public float cost() {
        return super.getPrice();
    }
}

public class LongBlack extends Coffee {
    public LongBlack() {
        setDes(" longblack ");
        setPrice(5.0f);
    }
}
//具体的Decorator, 这里就是调味品
public class Chocolate extends Decorator {
    public Chocolate(Drink obj) {
        super(obj);
        setDes(" 巧克力 ");
        setPrice(3.0f); // 调味品 的价格
    }
}
public class Milk extends Decorator {
    public Milk(Drink obj) {
        super(obj);
        setDes(" 牛奶 ");
        setPrice(2.0f); 
    }
}

Guess you like

Origin www.cnblogs.com/chao-zjj/p/11300518.html