策略模式

 

策略模式:

        它定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法的变化不会影响到使用算法的客户。

意图:

        同一函数接口实现不同的算法。

角色及职责:

        抽象策略类(Strategy):提供这一系列算法的统一函数接口。

        具体策略类(Concrete Strategy):根据需求实现的不同算法。

        环境类(Context):策略管理类,设置当前策略。

特点

    优点:

        1、 简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。
   2、 避免程序中使用多重条件转移语句,使系统更灵活,并易于扩展。
        3、 遵守大部分GRASP原则和常用设计原则,高内聚、低偶合。

    缺点:

        1、 因为每个具体策略类都会产生一个新类,所以会增加系统需要维护的类的数量。
        2、 在基本的策略模式中,选择所用具体实现的职责由客户端对象承担,并转给策略模式的Context对象。

典型例子:

        计算器+ - * /运算

示例代码:

//strategy抽象类,用作接口
class Strategy
{
public:
	virtual string substitute(string str)=0;
	virtual ~Strategy()
	{
		cout<<" in the destructor of Strategy"<<endl;
	}
};

class ChineseStrategy:public Strategy
{
public:
	string substitute(string str)
	{
		int index=str.find("520");
		string tempstr=str.replace(index,3,"我爱你");
		return tempstr;
	}
	~ChineseStrategy()
	{
		cout<<"in the destructor of ChineseStrategy"<<endl;
	}
};

class EnglishStrategy:public Strategy
{
public:
	string substitute(string str)
	{
		int index=str.find("520");
		string tempstr=str.replace(index,3,"i love ou");
		return tempstr;
	}
	~EnglishStrategy()
	{
		cout<<" in the destructor of ChineseStrategy"<<endl;
	}
};

//Context类
class Translator
{
private:
	auto_ptr<Strategy> strategy;
         //在客户代码中加入算法(stategy)类型的指针。
public:
	~Translator()
	{
		cout<<" in the destructor of Translator"<<endl;
	}
	void set_strategy(auto_ptr<Strategy> strategy)
	{
		this->strategy=strategy;
	}
	string translate(string str)
	{
		if(0==strategy.get())
			return "";
		return strategy->substitute(str);
	}
};

int main(int argc, char *argv)
{
	string str("321520");
	Translator *translator=new Translator;
	//未指定strategy的时候
	cout<<"No Strategy"<<endl;
	translator->translate(str);
	cout<<"---------------"<<endl;
	
	//翻译成中文
	auto_ptr<Strategy> s1(new ChineseStrategy);
	translator->set_strategy(s1);
	cout<<"Chinese Strategy"<<endl;
	cout<<translator->translate(str)<<endl;
	cout<<"---------------"<<endl;

	//翻译成英文
	auto_ptr<Strategy> s2(new EnglishStrategy);
	translator->set_strategy(s2);
	cout<<"English Strategy"<<endl;
	cout<<translator->translate(str)<<endl;
	cout<<"----------------"<<endl;

	delete translator;
	return 0;

}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值