java 装饰器模式
时间: 2023-11-12 19:59:08 浏览: 43
装饰器模式是一种结构型设计模式,它允许你通过将对象放入包含行为的特殊封装对象中来为原对象绑定新的行为。在装饰器模式中,这些封装对象称为装饰器。
在 Java 中,装饰器模式通常用于动态地修改对象的运行时行为,而不是在编译时就静态地修改代码。这种模式可以让你在不改变一个对象的前提下给其增加新的功能。
具体实现时,装饰器类和被装饰类通常都实现同一个接口或继承同一个父类,这样可以保证它们之间的互换性。
下面是一个简单的示例代码:
```java
interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() {
System.out.println("ConcreteComponent.operation()");
}
}
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation(); }
}
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("ConcreteDecoratorA.operation()");
}
}
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
public void operation() {
super.operation();
System.out.println("ConcreteDecoratorB.operation()");
}
}
public class Main {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component = new ConcreteDecoratorA(component);
component = new ConcreteDecoratorB(component);
component.operation();
}
}
```
输出结果为:
```
ConcreteComponent.operation()
ConcreteDecoratorA.operation()
ConcreteDecoratorB.operation()
```
这个示例中,`Component` 接口定义了一个 `operation()` 方法,`ConcreteComponent` 类实现了这个接口并提供了具体的实现。`Decorator` 类也实现了 `Component` 接口,并在其构造函数中接收一个 `Component` 对象,它的 `operation()` 方法会调用被装饰对象的 `operation()` 方法。`ConcreteDecoratorA` 和 `ConcreteDecoratorB` 类都继承自 `Decorator` 类,并在其 `operation()` 方法中先调用父类的 `operation()` 方法,再添加自己的行为。