装饰器模式
装饰者模式定义
装饰者模式:动态的将新功能附加到对象上。在对象功能扩展方面,它比继承更 有弹性,装饰者模式也体现了开闭原则(ocp) 这里提到的动态的将新功能附加到对象和ocp原则
装饰器模式比较适合多对多属性的组合模式
例如 咖啡 有 多种类型的咖啡 咖啡的配料又有多种类型的配料,糖,牛奶..咖啡和配料可以任意组合
可以抽象以一个咖啡的接口或抽象类,将配料抽象出一个抽象类,将咖啡组合入配料中。
public class Demo {
public static void main(String[] args) {
double v = new Soy(new Milk(new ShortBlack())).orderPrice();
System.out.println(v);
}
}
/**
* 抽象出一个饮料类
*/
abstract class Drink {
protected double price;
protected String name;
abstract double orderPrice();
}
class ShortBlack extends Drink {
public ShortBlack() {
this.name = "ShortBlack";
this.price=1;
}
@Override
double orderPrice() {
return this.price;
}
}
/**
* 配料抽象类
*/
class Decorator extends Drink{
protected Drink drink;
protected double price;
@Override
double orderPrice() {
return 0;
}
}
class Milk extends Decorator {
public Milk(Drink drink) {
this.price = 2;
this.drink=drink;
}
@Override
double orderPrice() {
return this.drink.orderPrice()+this.price;
}
}
class Soy extends Decorator {
public Soy(Drink drink) {
this.price = 3;
this.drink=drink;
}
@Override
double orderPrice() {
return this.drink.orderPrice()+this.price;
}
}