装饰器模式允许你通过将对象放入包含行为的特殊包装对象中来为原对象动态添加新的行为。以下是一个简单的 Java 示例:
// 定义接口
interface Component {void operation();
}// 具体组件实现接口
class ConcreteComponent implements Component {public void operation() {System.out.println("ConcreteComponent: operation()");}
}// 装饰器类,实现接口并持有一个 Component 对象
abstract class Decorator implements Component {protected Component component;public Decorator(Component component) {this.component = component;}public void operation() {component.operation();}
}// 具体装饰器类,扩展 Decorator 类
class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component) {super(component);}public void operation() {super.operation();System.out.println("ConcreteDecoratorA: additional operation()");}
}// 另一个具体装饰器类
class ConcreteDecoratorB extends Decorator {public ConcreteDecoratorB(Component component) {super(component);}public void operation() {super.operation();System.out.println("ConcreteDecoratorB: additional operation()");}
}// 示例
public class Main {public static void main(String[] args) {// 创建具体组件Component component = new ConcreteComponent();// 使用装饰器包装组件,并连续添加装饰器Component decoratedComponent = new ConcreteDecoratorA(new ConcreteDecoratorB(component));// 调用操作decoratedComponent.operation();}
}
在这个例子中,Component 接口定义了操作方法 operation(),ConcreteComponent 是具体组件实现了该接口。Decorator 是装饰器抽象类,持有一个 Component 对象,并实现了 operation() 方法来委托给被装饰的组件。ConcreteDecoratorA 和 ConcreteDecoratorB 是具体装饰器类,它们扩展了 Decorator 并添加了额外的操作。
在 Main 类中,我们首先创建了一个具体组件 ConcreteComponent,然后通过创建装饰器链将其包装,最后调用操作方法。由于装饰器链的存在,实际执行时会先执行 ConcreteDecoratorB 的操作,然后再执行 ConcreteDecoratorA 的操作,最后执行具体组件的操作。