设计模式总篇-策略模式

/*
@作者:莫忘输赢
@时间:
   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;
}
发布了141 篇原创文章 · 获赞 1 · 访问量 5327

猜你喜欢

转载自blog.csdn.net/wjl18270365476/article/details/104409024
今日推荐