使用缘由:
装饰者模式动态将职责(装饰者)附加到对象(被装饰者)上,在扩展功能方面,装饰者提供了比继承更具弹性的代替方案。
适用原则:
A:多用组合,少用继承。
B:对扩展开放,对修改封闭。
设计要点:
A:职责与对象有共同的超类或接口。
B:可用一个或多个职责装饰对象。
C:职责可以在被加载到对象之前,对自己添加职责。
D:对象可以在任何时候被职责装饰,所以可以在运行时动态的,不限量的用你喜欢的职责来装饰对象。
E:装饰模式中使用继承的关键是想达到职责和对象的类型匹配,而不是获得其行为。
Component:
定义一个对象接口,可以给这些对象动态地添加职责
public interface Component {
public void operation();
}
ConcreteComponent:
定义一个对象,可以给这个对象添加一些职责。
public class ConcreteComponent implements Component {
public void operation() {
// Write your code here
}
}
Decorator:
一个指向Component对象的引用,并定义一个与 Component接口一致的接口
public class Decorator implements Component {
@Override
public void operation() {
if (null != mComponent) {
mComponent.operation();
}
}
public void setComponent(Component component) {
mComponent = component;
}
protected Component mComponent = null;
}
ConcreteDecoratorA是Decorator的具体实现,具体职责A
public class ConcreteDecoratorA extends Decorator {
@Override
public void operation() {
super.operation();
mAddedState = "new state";
System.out.println("具体装饰对象A的操作");
}
private String mAddedState;
}
同理,ConcreteDecoratorB是Decorator的具体实现,具体职责B
public class ConcreteDecoratorB extends Decorator {
@Override
public void operation() {
super.operation();
addedBehavior();
System.out.println("具体装饰对象B的操作");
}
private void addedBehavior() {
System.out.println("来自ConcreteDecoratorB的addedBehavior方法");
}
}
其后将职责A和职责B按要求串接,并赋给对象ConcreteComponent
ConcreteComponent people = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
d1.setComponent(people);
d2.setComponent(d1);
d2.operation();
可以将用户要求的职责按顺序调用。
总结:
装饰者模式为已有的功能动态的添加更多功能的一种模式,新添加的功能完善了原有代码的核心职责和主要行为。装饰者模式将要装饰的功能(类似的功能)放到单独的类中,并让这个类包装其索要装饰的对象,当需要有选择的执行不同装饰功能时,按顺序的添加装饰功能的类即可。