用java写一个装饰器模式,并说明代码
时间: 2024-04-16 12:24:21 浏览: 11
当我们想要为一个对象动态地添加一些额外的行为或功能时,可以使用装饰器模式。下面是一个使用Java实现的装饰器模式示例代码:
```java
// 定义一个接口,表示被装饰的组件
public interface Component {
void operation();
}
// 实现组件的具体类
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("执行具体组件的操作");
}
}
// 定义装饰器类,实现与被装饰组件相同的接口
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
// 具体的装饰器类A
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
additionalOperationA();
}
private void additionalOperationA() {
System.out.println("执行具体装饰器A的附加操作");
}
}
// 具体的装饰器类B
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
additionalOperationB();
}
private void additionalOperationB() {
System.out.println("执行具体装饰器B的附加操作");
}
}
// 客户端使用装饰器模式
public class Client {
public static void main(String[] args) {
// 创建具体组件
Component component = new ConcreteComponent();
// 使用具体装饰器A装饰组件
Component decoratedComponentA = new ConcreteDecoratorA(component);
decoratedComponentA.operation();
System.out.println("------");
// 使用具体装饰器B装饰组件
Component decoratedComponentB = new ConcreteDecoratorB(component);
decoratedComponentB.operation();
System.out.println("------");
// 使用具体装饰器A和B同时装饰组件
Component decoratedComponentAB = new ConcreteDecoratorA(new ConcreteDecoratorB(component));
decoratedComponentAB.operation();
}
}
```
在这个例子中,`Component` 接口定义了被装饰的组件的操作方法。`ConcreteComponent` 是具体的组件类,实现了 `Component` 接口。
`Decorator` 是装饰器的抽象类,实现了 `Component` 接口,并持有一个 `Component` 对象作为成员变量。它通过调用被装饰组件的操作方法来实现其自身的操作。
`ConcreteDecoratorA` 和 `ConcreteDecoratorB` 是具体的装饰器类,继承自 `Decorator`。它们在调用被装饰组件的操作方法前后,分别执行了自己的附加操作。
在客户端代码中,我们可以创建具体组件对象,并使用不同的装饰器类来装饰该组件。通过装饰器模式,我们可以动态地给组件添加额外的功能,而无需对原有组件结构进行修改。