装饰器模式详解
定义
装饰器模式(Decorator Pattern)是一种结构型设计模式,允许动态地向对象添加新功能,而不改变其结构。装饰器模式通过将对象放入包含行为的新对象中,解决了继承的局限性。
核心思想:通过创建一个装饰类,用来包装原有的类,并在保持类方法签名完整的同时,增强其功能。
示例代码Java 实现:
// 基础接口
interface Component {
void operation();
}
// 基础实现类
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("基本功能");
}
}
// 抽象装饰器
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
// 具体装饰器A
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
System.out.println("装饰器A增强功能");
}
}
// 具体装饰器B
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
System.out.println("装饰器B增强功能");
}
}
// 测试
public class Main {
public static void main(String[] args) {
Component component = new ConcreteComponent(); // 原始组件
Component decoratedComponentA = new ConcreteDecoratorA(component); // 添加装饰器A
Component decoratedComponentB = new ConcreteDecoratorB(decoratedComponentA); // 添加装饰器B
decoratedComponentB.operation(); // 执行最终功能
}
}
输出:
基本功能
装饰器A增强功能
装饰器B增强功能
使用场景
- 动态扩展对象的功能:
-
- 当需要为一个对象添加功能,但不希望通过继承或修改已有类来实现。
- 职责分离:
-
- 将核心功能与附加功能分开,实现松耦合。
- 在运行时组合行为:
-
- 根据不同需求动态地组合各种功能。
源码中的应用
- Java I/O 流
-
- Java 的 I/O 流类库大量使用了装饰器模式,例如
InputStream
、OutputStream
和其装饰类BufferedInputStream
、DataInputStream
等。
- Java 的 I/O 流类库大量使用了装饰器模式,例如
InputStream input = new FileInputStream("file.txt");
InputStream bufferedInput = new BufferedInputStream(input);
InputStream dataInput = new DataInputStream(bufferedInput);
- Spring Framework
-
BeanWrapper
:在 Spring 中用于包装 JavaBean,动态地为其添加功能。- AOP (Aspect-Oriented Programming) :Spring AOP 本质上就是通过代理模式和装饰器模式实现,动态增强对象功能。
- Golang 的 HTTP Handler
-
- 在 Go 的 HTTP 中,
http.Handler
接口可以通过装饰器动态地添加功能,例如日志、鉴权等。
- 在 Go 的 HTTP 中,
应用场景
- UI 框架:
-
- 为图形组件(如按钮、文本框)添加功能,如滚动条、边框、阴影等。
- 日志记录:
-
- 为日志类动态地添加功能,比如格式化、加密或输出到不同目标。
- 安全校验:
-
- 在访问方法之前动态添加权限检查逻辑。
- 数据处理:
-
- 动态为数据流(如文件、网络流)添加处理能力,如压缩、加密或校验。
优缺点
优点:
- 动态扩展对象功能,无需修改类。
- 遵循开闭原则(OCP)。
- 可以组合多个装饰器,灵活性高。
缺点:
- 增加了系统的复杂性。
- 创建过多的装饰器类可能会使代码难以维护。