为已有功能动态添加更多功能的一种方式
客户端可以根据需要,有选择地,按顺序地使用装饰功能包装对象。
Decorator 继承了Component ,ConcreteDecorator 给具体的 ConcreteComponent 进行装饰,添加新的功能或职责。
Component类
public interface Component {
void Operation();
}
ConcreteComponent类
public class ConcreteComponent implements Component {
@Override
public void Operation() {
System.out.println("具体操作对象");
}
}
ConcreteDecorator
public abstract class Decorator implements Component {
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
@Override
public void Operation() {
if (component != null) {
component.Operation();
}
}
}
public class ConcreteDecoratorA extends Decorator {
private String addedState;
@Override
public void Operation() {
super.Operation();
addedState="new state";
System.out.println("具体装饰对象A操作");
}
}
public class ConcreteDecoratorB extends Decorator {
@Override
public void Operation() {
super.Operation();
addBehavior();
System.out.println("具体装饰对象B操作");
}
private void addBehavior() {
}
}
客户端调用
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
ConcreteDecoratorA decoratorA = new ConcreteDecoratorA();
ConcreteDecoratorB decoratorB = new ConcreteDecoratorB();
// 具体装饰类A 修饰 ConcreteComponent
decoratorA.setComponent(component);
// 具体装饰类B 再修饰 装饰类A
decoratorB.setComponent(decoratorA);
decoratorB.Operation();
/**
* 具体操作对象
* 具体装饰对象A操作
* 具体装饰对象B操作
*/
}
}