装饰模式(Decorator Pattern):动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。装饰模式是一种对象结构型模式。
//首先,定义一个组件接口:
public interface Component {
void operation();
}
//然后,创建一个实现了该接口的具体组件类
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("ConcreteComponent operation");
}
}
//接下来,创建一个抽象装饰器类,它实现了相同的接口并持有一个组件对象的引用:
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
//最后,创建具体装饰器类,继承自抽象装饰器并添加额外功能:
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunctionalityA();
}
public void addedFunctionalityA() {
System.out.println("Added functionality A");
}
}
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunctionalityB();
}
public void addedFunctionalityB() {
System.out.println("Added functionality B");
}
}
现在,你可以创建客户端代码来展示如何使用装饰器:
public class DecoratorPatternExample {
public static void main(String[] args) {
Component component = new ConcreteComponent();
System.out.println("Operation of ConcreteComponent:");
component.operation();
System.out.println("\nDecorating with ConcreteDecoratorA:");
component = new ConcreteDecoratorA(component);
component.operation();
System.out.println("\nDecorating with ConcreteDecoratorB:");
component = new ConcreteDecoratorB(component);
component.operation();
}
}