英文名称
Strategy 主要目的
定义一系列算法,把它们一个一个封装起来,并且使它们可以相互替换。策略使得算法可以独立于使用它的客户而变化。 使用场景
1.许多相关的类仅仅是行为有差别;
2.需要使用一个算法的不同变体时;
3.算法使用了客户不需要的数据。通过策略模式,可以避免暴露于算法有关的数据结构;
4.一个类定义了多种行为,并且这些行为在这个类的操作中是以多个判断语句的形式出现的。
测试平台
1.开发语言:C++
2.开发工具:VS2015
3.操作系统:Win7 X64 代码说明
1.Strategy–抽象策略类,用来定义抽象接口;
2.ConcreateStrategyNormal、ConcreateStrategySilver、ConcreateStrategyGold–具体策略类,继承于抽象策略类,实现不同的计算策略;
3.Context–上下文类,用一个具体策略来配置,实现不同策略的调用。
注意:
1.本例用策略模式来实现理发店消费金额结算;
2.通过策略模式,我们可以直接调整具体的策略,而不影响外部调用。
具体代码
#includeusing namespace std; //本例用策略模式来实现理发店消费金额结算 //结算规则如下: //普通会员:打9.5折 //银牌会员:打8折 //金牌会员:打6折 //抽象算法类,用来定义抽象接口 class Strategy { public: //函数功能:抽象结账接口 //参数: const int iMonetary[IN]-- 消费金额 //返回值: 无 virtual void CheckOutInterface(const int iMonetary) = 0; }; //普通会员结账策略,具体策略类,继承于抽象策略类 class ConcreateStrategyNormal :public Strategy { public: //函数功能:普通会员结账策略 //参数: const int iMonetary[IN]-- 消费金额 //返回值: 无 void CheckOutInterface(const int iMonetary) { cout << "客户类型:" << "普通会员" << endl; cout << "结算金额:" << iMonetary*0.95 << endl; } }; //银牌会员结账策略,具体策略类,继承于抽象策略类 class ConcreateStrategySilver :public Strategy { public: //函数功能:银牌会员结账策略 //参数: const int iMonetary[IN]-- 消费金额 //返回值: 无 void CheckOutInterface(const int iMonetary) { cout << "客户类型:" << "银牌会员" << endl; cout << "结算金额:" << iMonetary*0.8 << endl; } }; //金牌会员结账策略,具体策略类,继承于抽象策略类 class ConcreateStrategyGold :public Strategy { public: //函数功能:金牌会员结账策略 //参数: const int iMonetary[IN]-- 消费金额 //返回值: 无 void CheckOutInterface(const int iMonetary) { cout << "客户类型:" << "金牌会员" << endl; cout << "结算金额:" << iMonetary*0.6 << endl; } }; //Context类,上下文类,用一个具体策略来配置,实现不同策略的调用 class Context { public: //函数功能:构造函数 //参数: Strategy* pStrategy[IN]-- 具体策略 //返回值: 无 Context(Strategy* pStrategy) { this->m_pStrategy = pStrategy; } //函数功能:析构函数,释放指针 //参数: 无 //返回值: 无 ~Context() { if (this->m_pStrategy != NULL) { delete this->m_pStrategy; this->m_pStrategy = NULL; } } //函数功能:上下文接口,用于调用策略 //参数: 无 //返回值: 无 void ContextInterface(const int iMonetary) { if (this->m_pStrategy != NULL) { this->m_pStrategy->CheckOutInterface(iMonetary); } } private: Strategy* m_pStrategy; //具体策略的指针 }; int main() { int iMonetary = 200; //普通会员结算 cout << "顾客A消费金额:" << iMonetary << endl; Context* pContextNormal = new Context(new ConcreateStrategyNormal()); if (pContextNormal != NULL) { pContextNormal->ContextInterface(iMonetary); delete pContextNormal; pContextNormal = NULL; } cout << "*******************************************" << endl; //银牌会员结算 cout << "顾客B消费金额:" << iMonetary << endl; Context* pContextSilver = new Context(new ConcreateStrategySilver()); if (pContextSilver != NULL) { pContextSilver->ContextInterface(iMonetary); delete pContextSilver; pContextSilver = NULL; } cout << "*******************************************" << endl; //金牌会员结算 cout << "顾客C消费金额:" << iMonetary << endl; Context* pContextGold = new Context(new ConcreateStrategyGold()); if (pContextGold != NULL) { pContextGold->ContextInterface(iMonetary); delete pContextGold; pContextGold = NULL; } getchar(); return 0; }
输出结果