装饰者模式就是动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更有弹性,装饰者模式也体现了开闭原则。
装饰者模式就像打包一个快递
星巴克咖啡订单项目:
public abstract class Drink {
public String des;//描述
private float price = 0.0f;
//get、set方法
//计算费用的抽象方法
public abstract float cost();
}
public class Coffee extends Drink {
@Override
public float cost() {
return super.getPrice();
}
}
public class Espresso extends Coffee {
public Espresso(){
setDes("意大利咖啡");
setPrice(6.0f);
}
}
public class LongBlack extends Coffee {
public LongBlack() {
setDes("longBlack");
setPrice(5.0f);
}
}
public class ShortBlack extends Coffee {
public ShortBlack(){
setDes("shortBlack");
setPrice(4.0f);
}
}
public class Decorator extends Drink {
private Drink obj;
public Decorator(Drink obj) {
this.obj = obj;
}
@Override
public float cost() {
return super.getPrice() + obj.cost();
}
@Override
public String getDes() {
return super.getDes() + " " + super.getPrice() + "&&" + obj.getDes();
}
}
//这里就是调味品
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);
}
}
public class Soy extends Decorator {
public Soy(Drink obj) {
super(obj);
setDes("豆浆");
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.getDes());
//2、加入一份牛奶
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());
}
}
原文:https://www.cnblogs.com/fairboyllil/p/13409611.html