问题:
平时开发中经常会遇到在原来需求的基础上新增需求的情况。
比如实现排序,算法有很多种,冒泡、插入、堆排序、快排等等,其算法本身的特点决定了其适合的使用场景。
假设目前业务场景中,只使用了两种排序算法,新的场景出现后,需要新增一种算法。
- 如果使用一个方法实现所有的排序算法,通过if else 或case区分,代码会很臃肿,新代码添加以后要重写测试这个方法;
- 如果使用类封装,每个方法实现一种算法,类的规模会越来越大,并且每次新增客户要修改自己的代码,对客户来说,是一种困扰。
解决办法:
策略模式的使用,使算法的变化独立于客户。
如UML类图所示,算法子类继承自一个算法基类,新增一个Context类,算法放入Context类中,Context提供接口供客户使用具体算法。这样,具体算法的修改,对于客户来说是透明的。
代码实现:
Strategy.h
#ifndef STRATEGY_H
#define STRATEGY_H
class Strategy;
class Context {
public:
Context(Strategy *st);
~Context();
void ContextInterface();
private:
Strategy* m_Strategy;
};
class Strategy{
public:
virtual ~Strategy(){}
virtual void Algorithm() = 0;
};
class ConcreateStrategyA : public Strategy{
public:
virtual ~ConcreateStrategyA(){};
virtual void Algorithm();
};
#endif //STRATEGY_H
Strategy.cpp
#include "Strategy.h"
#include <iostream>
Context::Context(Strategy *st):m_Strategy(st)
{
}
Context::~Context()
{
if (m_Strategy != NULL) {
delete m_Strategy;
}
}
void Context::ContextInterface()
{
if (m_Strategy != NULL)
{
m_Strategy->Algorithm();
}
}
void ConcreateStrategyA::Algorithm()
{
std::cout<<"from ConcreateStrategyA"<<std::endl;
}
main.cpp
#include "Strategy.h"
int main()
{
Strategy* st = new ConcreateStrategyA();
Context *c = new Context(st);
c->ContextInterface();
delete c;
return 0;
}