装饰模式
Decorator,动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
Component是定义个对象的接口,可以给这些对象动态地添加职责,ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,时无需知道Decorator的存在的。至于ConcreateDecoratr就是具体的装饰对象,起到给Component添加职责的功能。
来看看基本的代码实现。
Component类
public abstract class Component {
public abstract void Operatiron();
}
ConcreteComponent类
public class ConreteComponent extends Component {
@Override
public void Operation() {
System.out.println("具体对象的操作");
}
}
Decorator类
public abstract class Decorator extends Component {
protected Component component;
@Override
public void Operation() {
if(component != null){
component.Operation();
}
}
public void setComponent(Component component){
if(component != null){
this.component = component;
}
}
}
ConcreteDecoratorA类
public class ConcreteDecoratorA extends Decorator {
private String addedState;
public String getAddedState() {
return addedState;
}
public void setAddedState(String addedState) {
this.addedState = 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的操作");
}
private void addedBehavior(){
}
}
客户端测试代码
public class Test {
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
/*
* 装饰的方法是:首先用ConcreteComponent实例化对象c,
* 然后用ConcreteDecoratorA的实例化对象d1来包装才,
* 再用ConcreteDecoratorB的对象d2包装d1,
* 最终执行d2的Operation();
*/
d1.setComponent(c);
d2.setComponent(d1);
d2.Operation();
}
}
装饰模式是利用setComponent来对对象进行包装的。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。
如果只有一个ConcreteComponnet类而没有抽象的Componnet类,那么Decorator类可以是ConcreteComponent的一个子类。同样道理,如果只有一个ConcreteDecorator类那么就没有必要建立一个单独的Decorator类,而可以吧Decorator和ConcreteDecorator的责任合并成一个类。
装饰模式是为了已有功能动态地添加更多功能的一种方式。当系统需要新功能的时候,事项旧得类中添加新的代码。这些新加的代码通常装饰了原有类的核心职责或主要行为。