策略模式(Strategy):定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。
优点:
1、 简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
2、 避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。
3、 所以算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法与使用算法类之间的耦合。
缺点:
1、 因为每个具体策略类都会产生一个新类,所以会增加系统需要维护的类的数量。
2、 在基本的策略模式中,选择所用具体实现的职责由客户端对象承担,并转给策略模式的Context对象。
由于在基本的策略模式中,选择所用具体实现的职责由客户端对象承担,并转给了策略模式Context对象。这本身并没有接触客户端需要选择判断的压力,而策略模式与简单工程模式结合后,选择具体实现的职责也可以由Context来承担,这就最大化地减轻了客户端的职责。
// Strategy.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
/*************************************策略基类****************************************/
class StrategyBase//主要定义了虚函数
{
public:
virtual void multiWay_tour()=0;//说明是纯虚函数(没有实现的虚函数),必须如此声明
};
/*************************************具体策略类****************************************/
class StrategyFirstChild:public StrategyBase//策略子类,主要对父类定义的虚方法进行具体实现
{
public:
void multiWay_tour()
{
cout<<"I'll go tourism on feet"<<endl;
}
};
class StrategySecondChild:public StrategyBase//策略子类,主要对父类定义的虚方法进行具体实现
{
public:
void multiWay_tour()
{
cout<<"I'll go tourism by train"<<endl;
}
};
/*************************************调度类****************************************/
class Context //调度类,根据传进来的参数,选择具体某个策略----待优化<参考教程>
{
private:
StrategyBase *strategyChild;
public:
Context(StrategyBase *child)
{
strategyChild=child;
}
void multiWay_tour()
{
strategyChild->multiWay_tour();
}
};
/*************************************客户端****************************************/
int main()
{
cout<<"测试程序"<<endl;
//“具体策略类”只在定义多个“调度类”时使用
Context *Context_A=new Context(new StrategyFirstChild());
Context *Context_B=new Context(new StrategySecondChild();,
Context *Context_C=new Context(new StrategySecondChild());
//调用方法,只通过“调度类”实现,算法之间的差异已被屏蔽
Context_A->multiWay_tour();
Context_B->multiWay_tour();
Context_C->multiWay_tour();
<span style="white-space:pre"> </span>delete Context_A;
<span style="white-space:pre"> </span>delete Context_B;
<span style="white-space:pre"> </span>delete Context_C;
cout<<endl;
system("pause");
return 0;
}