装饰者模式就是动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更有弹性,装饰者模式也体现了开闭原则。
装饰者模式就像打包一个快递
- 被装饰者(Component):比如陶瓷、衣服;
- 装饰者(Decorator):比如报纸填充、塑料泡沫、纸板
案例
星巴克咖啡订单项目:
- 咖啡种类/单品咖啡:Espresso(意大利浓咖啡)、ShortBlack、LongBlack(美式咖啡)、Decaf(无因咖啡);
- 调料:Milk、Soy(豆浆)、Chocolate;
- 要求在扩展新的咖啡种类时,具有良好的扩展性、改动方便、维护方便;
- 使用OO的来计算不同种类咖啡的费用:客户可以点单品咖啡,也可以单品咖啡+调料组合。
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());
}
}