装饰者模式
- 动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活
结构图

- “Component 是定义一个对象接口,可以给这些对象动态地添加职责。
- ConcreteComponent 是定义了一个具体的对象,也可以给这个对象添加一些职责。
- Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。
- 至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能[DPE]。”
基本代码实现
Component类
public abstract class Component {
public abstract void Operation();
}
ConcreteComponent类
public class ConcreteComponent extends Component{
@Override
public void Operation() {
System.out.println("具体对象操作");
}
}
Decorator类
public abstract class Decorator extends Component{
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
@Override
public void Operation() {
if(component!=null){
component.Operation();
}
}
}
ConcreteDecoratorA类
public class ConcreteDecoratorA extends Decorator{
private String addedState;
@Override
public void Operation() {
super.Operation();
addedState="new State";
System.out.println("具体装饰对象A的操作");
}
}
ConcreteDecoratorB类
public class ConcreteDecoratorB extends Decorator{
@Override
public void Operation() {
super.Operation();
AddedBehavior();
System.out.println("具体装饰对象B的操作");
}
public void AddedBehavior(){
}
}
客户端代码
public class Client {
public static void main(String[] args) {
ConcreteComponent cc = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
d1.setComponent(cc);
d2.setComponent(d1);
d2.Operation();
}
}
总结
- 装饰模式是利用SetComponent来对对象进行包装的。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中[DPE]。
- 如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent 的一个子类。同样道理,如果只有一个ConcreteDecorator类,那么就没有必要建立一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。
- 装饰模式是为已有功能动态地添加更多功能的一种方式。当系统需要新功能的时候,是向旧的类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。
- 装饰模式把类中的装饰功能从类中搬移去除,这样可以简化原有的类。有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。