装饰者模式就是动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更有弹性,装饰者模式也体现了开闭原则。 装饰者模式就像打包一个快递
星巴克咖啡订单项目:
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();
}
public class Coffee extends Drink {
@Override
public float cost() {
return super.getPrice();
}
}
public class Espresso extends Coffee {
public Espresso() {
super.setDescription("意大利咖啡");
super.setPrice(3.0f);
}
}
public class LongBlack extends Coffee {
public LongBlack() {
setDescription("LongBlack");
setPrice(5.0f);
}
}
public class ShortBlack extends Coffee {
public ShortBlack() {
setDescription("ShortBlack");
setPrice(4.0f);
}
}
public class Decorator extends Drink{
private Drink object;
public Decorator(Drink object) {
this.object = object;
}
@Override
public float cost() {
//getPrice:自己的价格
return super.getPrice()+ object.cost();
}
public String getDescription() {
// object.getDescription() 被装饰者的描述
return description + " " + getPrice() + "&&" + object.getDescription();
}
}
public class Milk extends Decorator {
public Milk(Drink object) {
super(object);
setDescription("Milk");
setPrice(2.0f);
}
}
public class Chocolate extends Decorator {
public Chocolate(Drink object) {
super(object);
setDescription("巧克力");
setPrice(3.0f);
}
}
public class Soy extends Decorator {
public Soy(Drink object) {
super(object);
setDescription("豆浆");
setPrice(1.5f);
}
}
public class Client {
public static void main(String[] args) {
//装饰者模式下的订单:1份巧克力+1份牛奶的LongBlack
//1、点一份LongBlack
Drink order = new LongBlack();
System.out.println("费用="+order.cost());
System.out.println("描述="+order.getDescription());
//2、加入一份牛奶
order = new Milk(order);
System.out.println("order 加入一份牛奶 费用="+order.cost());
System.out.println("order 加入一份牛奶 描述="+order.getDescription());
//2、加入一份牛奶
order = new Milk(order);
System.out.println("order 加入一份牛奶 费用="+order.cost());
System.out.println("order 加入一份牛奶 描述="+order.getDescription());
//3、order加入一份巧克力
order=new Chocolate(order);
System.out.println("order 加入一份巧克力 费用="+order.cost());
System.out.println("order 加入一份巧克力 描述="+order.getDescription());
}
}