装饰者模式(Decorator Pattern)是一种结构型设计模式,它允许你动态地给一个对象添加一些额外的职责,就增加功能来说,装饰者模式相比生成子类更为灵活。在装饰者模式中,一个装饰类会包装一个对象(通常称为被装饰者),并为其添加一些新的功能。
装饰者模式包含以下几个角色:
- Component(抽象组件):定义一个对象接口,可以给这些对象动态地添加职责。
- ConcreteComponent(具体组件):实现Component接口,是装饰器可以装饰的对象。
- Decorator(抽象装饰器):继承自Component,持有对Component对象的引用,并定义与Component接口一致的接口。
- ConcreteDecorator(具体装饰器):实现Decorator接口,负责给Component添加职责。
装饰者模式的特点:
- 装饰者和被装饰者对象有相同的超类型(接口或者抽象类)。
- 你可以用一个或多个装饰者包装一个对象。
- 装饰者可以在所委托被装饰者的行为之前与/或之后,加上自己的行为,以达到特定的目的。
- 对象可以在任何时候被装饰,所以可以在运行时动态地、不限量地用你喜欢的装饰者来装饰对象。
以下是一个简单的Java装饰者模式示例:
// 抽象组件(Component)
public interface Component {
void operation();
}
// 具体组件(ConcreteComponent)
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("执行基础操作");
}
}
// 抽象装饰器(Decorator)
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
if (component != null) {
component.operation();
}
}
}
// 具体装饰器A(ConcreteDecoratorA)
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunctionA();
}
public void addedFunctionA() {
System.out.println("为操作添加功能A");
}
}
// 具体装饰器B(ConcreteDecoratorB)
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedFunctionB();
}
public void addedFunctionB() {
System.out.println("为操作添加功能B");
}
}
// 客户端(Client)
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
// 使用装饰器A包装
ConcreteDecoratorA decoratorA = new ConcreteDecoratorA(component);
decoratorA.operation(); // 执行基础操作,并添加功能A
// 使用装饰器B包装装饰器A
ConcreteDecoratorB decoratorB = new ConcreteDecoratorB(decoratorA);
decoratorB.operation(); // 执行基础操作,添加功能A,并再添加功能B
}
}
在这个例子中,ConcreteComponent
是具体组件,它实现了Component
接口中的operation()
方法。Decorator
是抽象装饰器,它持有一个Component
对象的引用,并提供了operation()
方法的默认实现,即调用被装饰者的operation()
方法。ConcreteDecoratorA
和ConcreteDecoratorB
是具体装饰器,它们分别添加了不同的功能(addedFunctionA()
和addedFunctionB()
)。在客户端代码中,你可以看到如何使用装饰器来动态地给对象添加职责。