【设计模式】行为型模式-Strategy模式
# 功能
定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换
# 解决
- 主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护
- 何时使用:一个系统有许多许多类,而区分它们的只是他们直接的行为
- 如何解决:将这些算法封装成一个一个的类,任意地替换
- 关键代码:实现同一个接口
# 优缺点
- 优点:
- 算法可以自由切换
- 避免使用多重条件判断
- 扩展性良好
- 缺点:
- 策略类会增多
- 所有策略类都需要对外暴露
# 应用场景
- 应用实例:
- 旅行的出游方式,选择骑自行车、坐汽车,每一种旅行方式都是一个策略
- JAVA AWT 中的 LayoutManager
- 使用场景:
- 如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为
- 一个系统需要动态地在几种算法中选择一种。
- 如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现
- 注意事项:如果一个系统的策略多于四个,就需要考虑使用混合模式,解决策略类膨胀的问题
# 简单示例代码部分
Strategy.hpp
#ifndef _STRATEGY_H_
#define _STRATEGY_H_
#include <iostream>
using namespace std;
class Strategy{
public:
Strategy(){}
virtual ~Strategy(){
cout<<"~Strategy....."<<endl;
}
virtual void AlgrithmInterface() = 0;
};
class ConcreteStrategyA:public Strategy {
public:
ConcreteStrategyA(){}
virtual ~ConcreteStrategyA(){
cout<<"~ConcreteStrategyA....."<<endl;
}
void AlgrithmInterface(){
cout<<"test ConcreteStrategyA....."<<endl;
}
};
class ConcreteStrategyB:public Strategy {
public:
ConcreteStrategyB(){}
virtual ~ConcreteStrategyB(){
cout<<"~ConcreteStrategyB....."<<endl;
}
void AlgrithmInterface(){
cout<<"test ConcreteStrategyB....."<<endl;
}
};
/**
*这个类是 Strategy 模式的关键,也是 Strategy 模式和 Template 模式的根本区别所在。 *Strategy 通过“组合”(委托)方式实现算法 (实现)的异构,而 Template 模式则采取的 是继承的方式 *这两个模式的区别也是继承和组合两种实 现接口重用的方式的区别
*/
class Context
{
public:
Context(Strategy* stg){
_stg=stg;
}
~Context(){
if(!_stg)
delete _stg;
}
void DoAction(){
_stg->AlgrithmInterface();
}
private:
Strategy* _stg;
};
#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
49
50
51
52
53
54
55
56
57
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
53
54
55
56
57
Strategy.cpp
#include <iostream>
#include "Strategy.h"
using namespace std;
int main(){
Strategy* ps;
ps = new ConcreteStrategyA();
Context* pc = new Context(ps);
pc->DoAction();
if(NULL!=pc)
delete pc;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
编辑 (opens new window)
上次更新: 2022/05/18, 15:47:37