核心思想
装饰者模式允许在不修改原有类结构的前提下,动态地为对象添加新的行为或职责。相比通过继承创建子类来扩展功能,该模式提供了更高的灵活性和可维护性。
关键角色说明
- Component(组件接口):定义被装饰对象的公共接口,所有具体组件和装饰器都实现此接口。
- ConcreteComponent(具体组件):实现组件接口的具体类,代表原始功能的承载者。
- Decorator(装饰基类):抽象类,继承自Component,持有对Component实例的引用,并提供统一的装饰逻辑框架。
- ConcreteDecorator(具体装饰器):继承Decorator类,实现具体的增强逻辑,可在调用原方法前后插入额外行为。
典型实现代码(C#)
abstract class Component
{
public abstract void Execute();
}
class BasicService : Component
{
public override void Execute()
{
Console.WriteLine("执行基础服务");
}
}
abstract class ServiceWrapper : Component
{
protected Component innerService;
public void SetInnerService(Component service)
{
innerService = service;
}
public override void Execute()
{
if (innerService != null)
innerService.Execute();
}
}
class LoggingDecorator : ServiceWrapper
{
public override void Execute()
{
Console.WriteLine("[日志] 开始处理请求");
base.Execute();
Console.WriteLine("[日志] 请求处理完成");
}
}
class CachingDecorator : ServiceWrapper
{
public override void Execute()
{
Console.WriteLine("[缓存] 检查是否已有结果");
base.Execute();
Console.WriteLine("[缓存] 结果已保存");
}
}
客户端使用示例
static void Main(string[] args)
{
var basic = new BasicService();
var logging = new LoggingDecorator();
var caching = new CachingDecorator();
logging.SetInnerService(basic);
caching.SetInnerService(logging);
caching.Execute();
}
执行流程如下:
1. 输出"[缓存] 检查是否已有结果"
2. 输出"[日志] 开始处理请求"
3. 输出"执行基础服务"
4. 输出"[日志] 请求处理完成"
5. 输出"[缓存] 结果已保存"
适用场景
- 需要在运行时动态地为对象添加功能,且不想影响其他实例。
- 功能的组合方式较多,若使用继承会导致类爆炸。
- 希望保持原始类的简洁性,避免将多种职责耦合在一起。
优势与注意事项
- 无需修改已有代码即可扩展功能。
- 支持递归嵌套装饰,实现复杂的功能链。
- 每个装饰器职责单一,易于测试和复用。
- 过度使用可能导致对象结构复杂,难以追踪执行顺序。
C++版本示例
#include <iostream>
using namespace std;
class Device {
public:
virtual ~Device() = default;
virtual void Display() = 0;
};
class SmartPhone : public Device {
private:
string model;
public:
SmartPhone(const string& name) : model(name) {}
void Display() override {
cout << "显示手机:" << model << endl;
}
};
class Decorator : public Device {
protected:
Device* wrappedDevice;
public:
Decorator(Device* device) : wrappedDevice(device) {}
void Display() override {
if (wrappedDevice) wrappedDevice->Display();
}
};
class ScreenProtector : public Decorator {
public:
ScreenProtector(Device* device) : Decorator(device) {}
void Display() override {
Decorator::Display();
cout << "屏幕已贴膜" << endl;
}
};
class CaseDecorator : public Decorator {
public:
CaseDecorator(Device* device) : Decorator(device) {}
void Display() override {
Decorator::Display();
cout << "已安装保护壳" << endl;
}
};
int main() {
Device* phone = new SmartPhone("Xiaomi 14");
Device* withCase = new CaseDecorator(phone);
Device* withCaseAndScreen = new ScreenProtector(withCase);
withCaseAndScreen->Display();
delete withCaseAndScreen;
delete withCase;
delete phone;
return 0;
}