C++中的策略模式浅析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C++中的策略模式浅析

北冥有鱼丶丶   2023-03-23 我要评论

策略模式主要解决在有多种算法相似的情况下,使用 if…else 所带来的复杂和难以维护,其实际就是用来抽象变化的(和开放-封闭原则是一个原理),只要在分析过程中我们发现需要在不同的时间运用不同类型的业务规则或者代码中可能会出现很多变化,就可以考虑使用策略模式来处理这种变化。

策略模式通常的使用方法就是一个抽象策略类,若干具体策略类和一个Context类,同时Conetext类可以结合简单工厂模式让用户与策略类完全解耦,比如可以向Context类的构造函数中传入参数而不是策略类,然后在Conext的构造函数里用简单工厂模式根据传递的参数初始化策略类,甚至还可以什么都不传,定义一个默认策略供用户使用(简单工厂不一定是要一个单独的类)。Conetext类中包含一个策略类的指针指向简单工厂实例化出的具体策略类对象,还包含一个contextDeloy接口用于通过策略类指针去调用实例化出的具体策略类对象的接口,可以让用户面对Context的接口编程,而不与策略类接口直接耦合 ,方便策略类日后更改接口,同时还需要一个get接口,用于获取简单工厂中实例化出的对象。在业务逻辑层,我们先判断简单工厂模式实例化的具体对象是否为空,如果不为空,我们就可以通过contextDeloy接口去访问实例化的具体策略类对象的接口。

其实之前的这篇博客https://blog.csdn.net/weixin_44049823/article/details/128907849中,计算器5.0版本就已经使用了策略模式,在这篇博客中,我们共实现了计算器的5个版本,最初使用的是简单粗暴的if-else-if语句来判断使用哪一种业务(运算),到5.0版本,我们抽象出了一个Operation类(策略类),然后又创建了4个具体类,加法运算、减法运算、乘法运算、除法运算类(4个具体策略类),最后创建了一个工厂类用于根据不同情况实例化不同运算类的对象,其实这之中的一个抽象策略类和4个具体策略类已经有策略模式的影子了,但是缺少了其精华Context类。

接下来我将用策略模式改写之前的计算器5.0版本。

#include<iostream>
using namespace std;
#include<string>
//业务逻辑
//异常类用于处理异常情况
class opeException
{
public:
	void getMessage()
	{
		cout << "您的输入有误!" << endl;
	}
};
//运算类
class Operation
{
	//判断一个字符串是不是数字
	bool isStringNum(string& s)
	{
		bool flag = true;
		for (auto e : s)
			if (!(isdigit(e)))
			{
				flag = false;
				break;
			}
		return flag;
	}
protected:
	bool isError(string& _strNum1, string& _strNum2, string& _ope)
	{
		if (!(Operation::isStringNum(_strNum1) && Operation::isStringNum(_strNum2) && (_ope == "+" || _ope == "-" || _ope == "*" || _ope == "/")))
		{
			return false;
		}
	}
public:
	virtual int getResult()
	{
		return 0;
	}
};
//加法运算类
class addOperation :public Operation
{
private:
	string strNum1;
	string strNum2;
	string ope;
	int re;
public:
	addOperation(string& _strNum1, string& _strNum2, string& _ope) :strNum1(_strNum1), strNum2(_strNum2), ope(_ope), re(0) {}
	virtual int getResult() override
	{
		if (!isError(strNum1, strNum2, ope))
			throw opeException();
		else
			re = stoi(strNum1) + stoi(strNum2);
		return re;
	}
};
//减法运算类
class subOperation :public Operation
{
private:
	string strNum1;
	string strNum2;
	string ope;
	int re;
public:
	subOperation(string& _strNum1, string& _strNum2, string& _ope) :strNum1(_strNum1), strNum2(_strNum2), ope(_ope), re(0) {}
	virtual int getResult() override
	{
		if (!isError(strNum1, strNum2, ope))
			throw opeException();
		else
			re = stoi(strNum1) - stoi(strNum2);
		return re;
	}
};
//乘法运算类
class mulOperation :public Operation
{
private:
	string strNum1;
	string strNum2;
	string ope;
	int re;
public:
	mulOperation(string& _strNum1, string& _strNum2, string& _ope) :strNum1(_strNum1), strNum2(_strNum2), ope(_ope), re(0) {}
	virtual int getResult() override
	{
		if (!isError(strNum1, strNum2, ope))
			throw opeException();
		else
			re = stoi(strNum1) * stoi(strNum2);
		return re;
	}
};
//除法运算类
class divOperation :public Operation
{
private:
	string strNum1;
	string strNum2;
	string ope;
	int re;
public:
	divOperation(string& _strNum1, string& _strNum2, string& _ope) :strNum1(_strNum1), strNum2(_strNum2), ope(_ope), re(0) {}
	virtual int getResult() override
	{
		if (!isError(strNum1, strNum2, ope))
			throw opeException();
		else if (stoi(strNum2) != 0)
			re = stoi(strNum1) / stoi(strNum2);
		else
			throw opeException();
		return re;
	}
};
//Conetext结合简单工厂模式
class Context
{
	Operation *operation;
public:
	Context(string& _strNum1, string& _strNum2, string& _ope)
	{
		if (_ope == "+")
		{
			operation = new addOperation(_strNum1, _strNum2, _ope);
		}
		else if (_ope == "-")
			operation = new subOperation(_strNum1, _strNum2, _ope);
		else if (_ope == "*")
			operation = new mulOperation(_strNum1, _strNum2, _ope);
		else if (_ope == "/")
		{
			operation = new divOperation(_strNum1, _strNum2, _ope);
		}
		else
			operation = nullptr;
	}
	Operation* get()
	{
		return operation;
	}
	int contextResult()
	{
		return operation->getResult();
	}
};
//界面逻辑
int main()
{
	try
	{
		string _strNum1 = " ";
		string _strNum2 = " ";
		string _ope = " ";
		cout << "请输入左操作数:" << endl;
		cin >> _strNum1;
		cout << "请输入右操作数:" << endl;
		cin >> _strNum2;
		cout << "请输入操作符:" << endl;
		cin >> _ope;
		Context context(_strNum1, _strNum2, _ope);
		if (context.get() != nullptr)
			cout << context.contextResult() << endl;
		else
			cout << "您的输入有误!" << endl;
	}
	catch (opeException ex)
	{
		cout << "您的输入有误" << endl;
	}
	return 0;
}

结合上一篇博客的5.0版本代码可知,简单工厂模式需要让客户端认识两个类,而策略类只需要让客户端认识一个类即可,耦合更低。

总结策略模式的优缺点:

优点:

1、算法可以自由切换。

2、避免使用多重条件判断。

3、扩展性良好。

缺点:

1、策略类会增多。

2、所有策略类都需要对外暴露。

注意事项:如果一个系统的策略多于四个,就需要考虑使用混合模式,解决策略类膨胀的问题。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们