【设计模式】结构型模式-Decorator模式
# 功能
允许向一个现有的对象添加新的功能,同时又不改变其结构。
# 解决
- 主要解决:为扩展一个类经常使用继承方法实现
- 何时使用:在不想增加很多子类的情况下扩展类
- 如何解决:将具体功能职责划分,同时继承装饰者模式
- 关键代码:
- Component 类充当抽象角色,不应该具体实现。
- 修饰类引用和继承 Component 类,具体扩展类重写父类方法。
# 优缺点
- 优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
- 缺点:多层装饰比较复杂
# 应用场景
- 应用实例:孙悟空有 72 变,当他变成"庙宇"后,他的根本还是一只猴子,但是他又有了庙宇的功能。
- 使用场景: 1、扩展一个类的功能。 2、动态增加功能,动态撤销。
- 注意事项:可替代继承
# 简单示例代码部分
Decorator.hpp
#ifndef _DECORATOR_H_
#define _DECORATOR_H_
#include <iostream>
class Component{
public:
virtual ~Component(){}
virtual void Operation(){}
protected:
Component(){}
};
class ConcreteComponent:public Component{
public:
ConcreteComponent(){}
~ConcreteComponent(){}
void Operation(){
std::cout<<"ConcreteComponent Operation...\n";
}
};
class Decorator:public Component{
public:
Decorator(Component* com){
this->_com=com;
}
virtual ~Decorator(){
delete _com;
}
void Operation(){}
protected:
Component* _com;
};
class ConcreteDecorator:public Decorator{
public:
ConcreteDecorator(Component* com):Decorator(com){}
virtual ~ConcreteDecorator(){}
void AddedBehavior(){
std::cout<<"ConcreteDecorator::AddedBehavior...\n";
}
void Operation(){
_com->Operation();
this->AddedBehavior();
}
};
#endif
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
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
main.cpp
#include "Decorator.hpp"
#include <iostream>
using namespace std;
int main(){
Component* com=new ConcreteComponent();
Decorator* dec=new ConcreteDecorator(com);
dec->Operation();
delete dec;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
编辑 (opens new window)
上次更新: 2022/05/18, 15:47:37