官方定义:
策略模式是一种定义一些列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类别与使用算法类之间的耦合。
自己理解:
用来避免设计的类中同时包含众多的实现,并且实现算法之间用开关型语句(例如:if else if, switch case 等)进行多级判断所导致的代码改写复用困难等问题。
UML图:
代码示例:
// Step1: 定义抽象策略类
class Strategy {
public:
virtual void AlgorithmInterface() = 0;
virtual ~Strategy() {}
};
//Step2: 定义具体策略类
class ConcreatStrategyA :public Strategy {
public:
void AlgorithmInterface() {
//具体代码实现
}
};
class ConcreatStrategyB :public Strategy {
public:
void AlgorithmInterface() {
//具体代码实现
}
};
class ConcreatStrategyC :public Strategy {
public:
void AlgorithmInterface() {
//具体代码实现
}
};
//Step3:定义上下文
class Context {
private:
Strategy* strategy;
public:
Context(Strategy* s) :strategy(s) {}
void ContextInterface() {
// 功能代码
strategy->AlgorithmInterface();
//功能代码
}
~Context() {
delete strategy;
}
};
//Step4: 定义客户端代码
int main() {
Context* context = new Context(new ConcreatStrategyA);
context->ContextInterface();
Context* context = new Context(new ConcreatStrategyB);
context->ContextInterface();
Context* context = new Context(new ConcreatStrategyC);
context->ContextInterface();
};