以下是使用Java编写装饰器模式(Decorator)的示例代码:
// 抽象产品类
abstract class Component {
public abstract void operation();
}
// 具体产品类
class ConcreteComponent extends Component {
@Override
public void operation() {
System.out.println("ConcreteComponent");
}
}
// 装饰器类
abstract class Decorator extends Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
// 具体装饰器类
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
System.out.println("ConcreteDecoratorA");
}
}
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
System.out.println("ConcreteDecoratorB");
}
}
// 客户端代码
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component decoratorA = new ConcreteDecoratorA(component);
Component decoratorB = new ConcreteDecoratorB(decoratorA);
decoratorB.operation();
}
}
在这个示例中,我们定义了一个抽象产品类Component,以及一个具体产品类ConcreteComponent。具体产品类实现了operation方法,用于执行具体操作。我们还定义了一个抽象装饰器类Decorator,以及两个具体装饰器类ConcreteDecoratorA和ConcreteDecoratorB。具体装饰器类继承了Decorator类,并重写了operation方法,用于在执行具体操作之前或之后进行额外的操作。客户端代码Client中,我们创建了一个ConcreteComponent对象component,然后创建了两个ConcreteDecorator对象decoratorA和decoratorB,并将它们串联起来。最后,我们调用decoratorB对象的operation方法,可以看到它先执行了ConcreteDecoratorA对象的operation方法,然后执行了ConcreteComponent对象的operation方法,最后执行了ConcreteDecoratorB对象的operation方法。
通过使用装饰器模式,我们可以轻松地为现有对象添加额外的功能,而无需修改现有对象或客户端代码。这使得装饰器更加灵活,可以装饰不同的产品对象以实现不同的功能。