strategy(策略模式)
策略模式主要应对的问题:
- 业务算法多变
- 许多类仅仅是行为不同
- 多个条件判断,并且条件个数有可能随着业务增加
结构图:

代码:
策略接口类:
- 对策略接口进行定义
//策略接口
class strategyInterface
{
public:
virtual void dealWay()=0;
};
具体策略
- 对具体策略进行实现
//具体策略的实现1
class strategyOne : public strategyInterface
{
public:
virtual void dealWay() {
cout<<"策略1"<<endl;
}
};
具体策略
- 对具体策略进行实现
//具体策略的实现2
class strategyTwo : public strategyInterface
{
public:
virtual void dealWay() {
cout<<"策略2"<<endl;
}
};
//使用策略的对象,拥有一个多态的策略指针,调用不同的策略
//策略使用者
class useStrategy
{
protected:
strategyInterface* strategy;
public:
//此处使用工厂模式更加好
useStrategy(strategyInterface* _strategy):strategy(_strategy)
{
}
void test()
{
strategy->dealWay();
}
};
test
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
useStrategy* us = new useStrategy(new strategyOne());
us->test();
useStrategy* us1 = new useStrategy(new strategyTwo());
us1->test();
return 0;
}

网友评论