设计模式总篇-策略模式

会有一股神秘感。 提交于 2020-02-20 17:37:52
/*
@作者:莫忘输赢
@时间:
   2020/2/10 12:46
@版本:v1

@策略模式
@作用
定义算法家族,分别封装起来,让它们相互替换,让算法变化不会影响到用户
@优点
每个算法都有自己的类,算法经常变动,简化单元测试,解决的事经常变动的算法
@缺点
客户端要做出判断

*/

#include <iostream>

//#include<vld.h>


//策略基类
class COperation
{
public:
	int fst;
	int sst;
public:
	virtual double GetRst()
	{
		int  dResult = 0;
		return 0;
	}
};

//策略方法类
class AddOperation : public COperation
{
public:
	AddOperation(int a, int b){
		fst = a;
		sst = b;
	}
	virtual double GetRst()
	{
		return fst + sst;
	}
};

//上下文
class Context
{
private:
	COperation *_op;
public:
	Context(char cType)
	{
		switch (cType)
		{
		case'+':
			_op = new AddOperation(3,8);
			break;
		default:
			break;
		}
	}

	double GetRst()
	{
		return _op->GetRst();
	}
	~Context()
	{
		if (_op != nullptr)
		{
			delete _op;
		}
	}
};

int main(int argc, char** argv)
{
	Context *text = new Context('+');
	std::cout<<text->GetRst()<<std::endl;

	delete text;
	text = nullptr;

	return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!