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