策略模式

策略模式

1.何为策略模式

​ 定义一系列算法,把它们封装起来,并使它们可以互相替换(变化),该模式使得算法可以独立于它的客户程序(稳定)而变化(拓展、子类化)。本质上是允许我们定义通用的算法框架,然后以组件的形式提供框架内部流程的具体实现。

2.策略模式的意义和使用场景

​ 在软件构建中,某些对象使用的算法可能多种多样,十分不稳定。策略模式将算法和对象本身解耦。策略模式为组件提供了一系列可重用的算法,从而可以使组件在运行时根据需要在各个算法直接切换,十分灵活。它消除提供了条件判断语句之外的另一种选择,这就是在解耦。根据性能需要,算法本身可以使用单例模式。

3.策略模式的实现。

​ 在抽象策略基类中定义算法接口。具体算法继承于该基类,去实现不同的算法。在组件中包含抽象策略基类的指针,创建对象时将具体算法传递给组件即可。

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
// 抽象策略类
class Strategy {
public:
virtual int doOperation(int num1, int num2) = 0;
};
// 具体策略类 - 加法策略
class AddStrategy : public Strategy {
public:
int doOperation(int num1, int num2) override {
return num1 + num2;
}
};
// 具体策略类 - 减法策略
class SubtractStrategy : public Strategy {
public:
int doOperation(int num1, int num2) override {
return num1 - num2;
}
};
// 上下文类 - 它包含一个策略对象,可以根据策略对象调用不同的方法
class Context {
private:
Strategy* strategy;

public:
Context(Strategy* strategy) : strategy(strategy) {}

void setStrategy(Strategy* strategy) {
this->strategy = strategy;
}

int executeStrategy(int num1, int num2) {
return strategy->doOperation(num1, num2);
}
};