C++中的策略模式浅析

 更新时间:2023年02月27日 08:58:53   作者:北冥有鱼丶丶  
策略模式属于C++设计模式中行为模式之一,该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换。本文将通过示例详细讲解这一模式,需要的可以参考一下

策略模式主要解决在有多种算法相似的情况下,使用 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、所有策略类都需要对外暴露。

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

到此这篇关于C++中的策略模式浅析的文章就介绍到这了,更多相关C++策略模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • C++ 数据结构之布隆过滤器

    C++ 数据结构之布隆过滤器

    这篇文章主要介绍了C++ 数据结构之布隆过滤器的相关资料,需要的朋友可以参考下
    2017-06-06
  • C语言实现飞机游戏(2)

    C语言实现飞机游戏(2)

    这篇文章主要介绍了C语言实现飞机游戏的第二部分,进行功能完善,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-05-05
  • C语言实现求解最小公倍数的算法示例

    C语言实现求解最小公倍数的算法示例

    这篇文章主要为大家介绍了C语言如何实现求解任意两个正整数的最小公倍数,文中采用了穷举法和定理法。感兴趣的小伙伴快来跟随小编一起学习学习吧
    2021-12-12
  • 在C++中使用HP-Socket

    在C++中使用HP-Socket

    这篇文章主要介绍了C++中简单使用HP-Socket,HP-Socket 是一套通用的高性能 TCP/UDP /HTTP 通信 框架 ,包含服务端组件、客户端组件和 Agent 组件,广泛适用于各种不同应用场景的 TCP/UDP /HTTP 通信系统,下面来看看更具体的介绍吧
    2021-11-11
  • 浅析C语言中strtol()函数与strtoul()函数的用法

    浅析C语言中strtol()函数与strtoul()函数的用法

    这篇文章主要介绍了浅析C语言中strtol()函数与strtoul()函数的用法,注意其将字符串转换成long型的区别,需要的朋友可以参考下
    2015-08-08
  • C语言实现二叉树层次遍历介绍

    C语言实现二叉树层次遍历介绍

    大家好,本篇文章主要讲的是C语言实现二叉树层次遍历介绍,感兴趣的同学赶快来看一看吧,对你有帮助的话记得收藏一下
    2022-01-01
  • C++实现单链表的构造

    C++实现单链表的构造

    这篇文章主要为大家详细介绍了C++实现单链表的构造,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-04-04
  • 浅谈Linux环境下并发编程中C语言fork()函数的使用

    浅谈Linux环境下并发编程中C语言fork()函数的使用

    fork函数在Linux中可以创建子进程即一个新的进程,这里我们根据实例来浅谈Linux环境下并发编程中C语言fork()函数的使用,需要的朋友可以参考下
    2016-06-06
  • VC外部符号错误_main,_WinMain@16,__beginthreadex解决方法

    VC外部符号错误_main,_WinMain@16,__beginthreadex解决方法

    这篇文章主要介绍了VC外部符号错误_main,_WinMain@16,__beginthreadex解决方法,实例分析了比较典型的错误及对应的解决方法,需要的朋友可以参考下
    2015-05-05
  • 如何在C++类的外部调用类的私有方法

    如何在C++类的外部调用类的私有方法

    这篇文章主要介绍了如何在C++类的外部调用类的私有方法,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的朋友可以参考一下
    2022-09-09

最新评论