2011年3月4日 星期五 〖农历 辛卯 免年 正月三十〗 晴 设计模式:策略模式适用范围:当算法完成的功能相同,只是实现不同时,可以使用,一般与工厂模式配合使用,效果更佳.应用实例:如商场促销,采用了如下的方案:1)正常收费2)八折3)买300返100元....策略模式的结构图如下:C++关键代码实现如下:1、父类:CStrategySuper.cpp//虚函数:double CStrategySuper::GetInstance(){ return 0;}2、子类:CStrategyA.cppdouble CStrategyA::GetInstance(){ //算法A的实现 return 1;}3、子类:CStrategyB.cppdouble CStrategyB::GetInstance(){ //算法B的实现 return 2;}4、子类:CStrategyC.cppdouble CStrategyC::GetInstance(){ //算法C的实现 return 3;}5、配置类:CContext.cpp//通过CStrategyA,B,C等子类来维护对父类CStrategy对象的引用。CContext::CContext(CStrategySuper *cs){ m_strategy = cs;}
CContext::~CContext()
{
if(strategy != NULL)
{
delete strategy ;
strategy = NULL;
}
}double CContext::ContextInterface(){ return m_strategy->GetInstance();}
6、客户端的实现main.cppCContext *context1 = new CContext(new CStrategyA());printf("strategyA:[%.1f]/n",context1->ContextInterface());
if(context1 != NULL)
{
delete context1;}context1 = new CContext(new CStrategyB());printf("strategyB:[%.1f]/n",context1->ContextInterface());
if(context1 != NULL)
{
delete context1;}context1 = new CContext(new CStrategyC());printf("strategyC:[%.1f]/n",context1->ContextInterface());
if(context1 != NULL)
{
delete context1;}
原书中所列的实现,商场促销的C++代码实现,如果有需要的话,可以联系我哦。呵呵~以上,如果有错误或不准备的地方,欢迎批评指正哦。我也是在刚刚学习中。。。呵呵~