装饰者模式:动态的给一个对象添加一些额外的职责,就增加功能来说, Decorator模式相比生成子类更为灵活。该模式以对客户端透明的方式扩展对象的功能。
参与者:
1. Component(被装饰对象的基类),定义一个对象接口,可以给这些对象动态地添加职责。
2. ConcreteComponent(具体被装饰对象),定义一个对象,可以给这个对象添加一些职责。
3. Decorator(装饰者抽象类),维持一个指向Component实例的引用,并定义一个与Component接口一致的接口。
4. ConcreteDecorator(具体装饰者),具体的装饰对象,给内部持有的具体被装饰对象,增加具体的职责。
类图
代码
Component(被装饰对象的基类)
// 表示价格的接口
public abstract class Price {
public abstract int getValue();
}
ConcreteComponent(具体被装饰对象)
// 表示价格的原价
public class PrimePrice extends Price {
private int value;
PrimePrice(int value){
this.value = value;
}
@Override
public int getValue(){
return this.value;
}
}
Decorator(装饰者抽象类)
// 定义原价的装饰器
public abstract class DecoratorPrice extends Price {
protected Price price;
public DecoratorPrice(Price price){
this.price = price;
}
@Override
public int getValue() {
return price.getValue();
}
}
ConcreteDecorator(具体装饰者)
// 采购价格2倍的价格提示Price
public class DoublePrice extends DecoratorPrice {
public DoublePrice(Price price) {
super(price);
}
@Override
public int getValue(){
return this.price.getValue()*2;
}
}
// 原价基础上追加的价格
public class WholesalePrice extends DecoratorPrice {
private int advantage;
public WholesalePrice(Price price, int advantage) {
super(price);
this.advantage = advantage;
}
@Override
public int getValue(){
return this.price.getValue() + advantage;
}
}
测试代码
public class DecoratorTest {
public static void main(String[] args) {
// 原价
PrimePrice prime = new PrimePrice(120);
// 原价基础上翻倍
DoublePrice doublePrice = new DoublePrice(prime);
// 翻倍基础上加价
WholesalePrice wholesale = new WholesalePrice(doublePrice, 20);
// 最后取得价格结果
int result = wholesale.getValue();
System.out.println(result);
}
}
这里也可以先加价,然后再翻倍,其实可以有很多不同的组合
装饰者模式小结
1. Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
2. 通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。