装饰(Decorator)模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。
一,结构
抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
具体装饰(Concrete Decorator)角色:负责给构件对象"贴上"附加的责任。
二,示例代码
/**
* 抽象构件
* @author Salmon
*
*/
public interface Component {
public void operation();
}
/**
* 具体构件
* @author Salmon
*
*/
public class ConcreteComponent implements Component {
public void operation() {
System.out.println("ConcreteComponent.Operation()");
}
}
/**
* 装饰(即组合又继承)
* @author Salmon
*
*/
public class Decorator implements Component {
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
public void operation() {
if (component != null)
component.operation();
}
}
/**
* 具体装饰
* @author Salmon
*
*/
public class ConcreteDecoratorA extends Decorator {
private String addedState;
public void operation() {
super.operation();
addedState = "new state";
System.out.println("ConcreteDecoratorA.Operation()");
}
}
/**
* 具体装饰
* @author Salmon
*
*/
public class ConcreteDecoratorB extends Decorator {
public void operation() {
super.operation();
AddedBehavior();
System.out.println("ConcreteDecoratorB.Operation()");
}
private void AddedBehavior() {
System.out.println("new state");
}
}
/**
* 客户代码
* @author Salmon
*
*/
public class Client {
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
d1.setComponent(c);
d2.setComponent(d1);
d2.operation();
}
}