装饰者模式(decorator pattern): 动态地将责任附加到对象上
意图:为对象动态添加功能
类图
实现
设计不同种类的饮料,饮料可以添加配料,比如可以添加牛奶,并且支持动态添加新配料。每增加一种配料,该饮料的价格就会增加,要求计算一种饮料的价格。
项目结构
bash
$ tree
.
├── Beverage.java # 接口
├── Client.java # 客户端调用方
└── impl
├── CondimentDecorator.java # 装饰器抽象类
├── DarkRoast.java # Beverage的实现类
├── HouseBlend.java # Beverage的实现类
├── Milk.java # 装饰器抽象类的实现类
└── Mocha.java # 装饰器抽象类的实现类
具体代码
java
public interface Beverage {
double cost();
}
java
public class DarkRoast implements Beverage {
@Override
public double cost() {
return 1;
}
}
java
public class HouseBlend implements Beverage {
@Override
public double cost() {
return 1;
}
}
java
public abstract class CondimentDecorator implements Beverage {
protected Beverage beverage;
}
java
public class Milk extends CondimentDecorator {
public Milk(Beverage beverage) {
this.beverage = beverage;
}
@Override
public double cost() {
return 1 + beverage.cost();
}
}
java
public class Mocha extends CondimentDecorator {
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public double cost() {
return 1 + beverage.cost();
}
}
java
public class Client {
public static void main(String[] args) {
Beverage beverage = new HouseBlend();
beverage = new Mocha(beverage);
beverage = new Milk(beverage);
System.out.println(beverage.cost());
// 3.0
}
}
参考文章