• Decorator(装饰者)模式

C++ Decorator 模式 详解

Decorator(装饰者)模式是一种结构型设计模式,它允许向一个对象动态地添加功能,而无需通过子类继承的方式。这种模式是通过将对象包装在一个装饰器类的实例中来实现的,这样就可以动态地添加新的行为和责任。

结构

Decorator模式包含以下几个关键角色:

  1. Component(组件):是一个抽象类或接口,定义了被装饰的对象的接口。它可以是一个具体的类或接口,定义了一些基本的行为。

  2. ConcreteComponent(具体组件):是实现Component接口的具体类,它是被装饰的对象。

  3. Decorator(装饰器):也是一个抽象类或接口,它继承了Component,并持有一个Component对象的引用。这个类的主要作用是为了动态地添加额外的功能。

  4. ConcreteDecorator(具体装饰器):是实现Decorator接口的具体类,它包含了要添加的额外功能。它可以包装具体组件对象并调用其原始的操作,然后再添加额外的功能。

实现示例

下面是一个简单的Decorator模式的实现示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>

// Component
class Coffee {
public:
    virtual void serve() const = 0;
};

// ConcreteComponent
class SimpleCoffee : public Coffee {
public:
    void serve() const override {
        std::cout << "Simple coffee" << std::endl;
    }
};

// Decorator
class CoffeeDecorator : public Coffee {
protected:
    Coffee* coffee;

public:
    CoffeeDecorator(Coffee* coffee) : coffee(coffee) {}

    void serve() const override {
        coffee->serve();
    }
};

// ConcreteDecorator
class MilkDecorator : public CoffeeDecorator {
public:
    MilkDecorator(Coffee* coffee) : CoffeeDecorator(coffee) {}

    void serve() const override {
        CoffeeDecorator::serve();
        std::cout << " + milk" << std::endl;
    }
};

int main() {
    Coffee* coffee = new SimpleCoffee();
    coffee->serve();  // Output: Simple coffee

    Coffee* coffeeWithMilk = new MilkDecorator(coffee);
    coffeeWithMilk->serve();  // Output: Simple coffee + milk

    delete coffee;
    delete coffeeWithMilk;

    return 0;
}

在这个示例中,Coffee是组件,SimpleCoffee是具体组件。CoffeeDecorator是装饰器,MilkDecorator是具体装饰器。

使用装饰器模式,我们可以在运行时动态地向SimpleCoffee对象添加额外的功能,而无需修改其原始类的代码。