解决if..else嵌套过多问题(涉及职责链模式)

1.函数表

1)适用于逻辑表达模式相似

2)形式 :map

3)


#include 
#include 
#include 
typedef int (*ifun)(int,int);
typedef double (*dfun)(double, double);
using namespace std;
//普通函数
double Add(double i, double j)
{
	return i + j;
 }

//函数类对象:c++标准库很多算法都是函数类对象
class Divide
{
public:
	double operator()(double i, double j )
	{
		return i / j;
	}
};

auto mul = [](double i, double j) {return i * j; };

int main()
{
	//只能存储普通函数,lambda和函数类对象无法存入
	std::map binops;

	//c++11的function:无法存储重载函数,只能通过函数指针或lamada解决
	std::map> mp;
	mp.insert({ "+", Add });
	mp.insert({ "/", Divide()});
	mp.insert({ "*", mul });
	cout<

2.职责链模式 

1)适用于逻辑表达模式不一样

2)实例

#include 
 
using namespace std;

//职责链重点在于设置接任者
class Handler
 {
 public:
	 Handler():_successor(nullptr){}
	 void setSuccessor(Handler *successor) { _successor = successor; }
	 virtual void handleRequest(int request) = 0;

 protected:
	 Handler *_successor;
 
 };

class Handler1 :public Handler
{
public:
	Handler1():_name("Handler1"){}

	virtual void handleRequest(int request) override
	{
		if (request > 0 && request <= 10)
		{
			//自己处理
			cout << _name << "处理结束" << endl;
		}
		else if(_successor)
		{
			//给接任者处理
			_successor->handleRequest(request);
		}
	}
private:
	string _name;
};

class Handler2 :public Handler
{
public:
	Handler2() :_name("Handler2") {}

	virtual void handleRequest(int request) override
	{
		if (request > 10 && request <= 20)
		{
			//自己处理
			cout << _name << "处理结束" << endl;
		}
		else if (_successor)
		{
			//给接任者处理处理
			_successor->handleRequest(request);
		}
	}
private:
	string _name;
};
int main()
{ 
	Handler *h1 = new Handler1();
	Handler *h2 = new Handler2();
	h1->setSuccessor(h2);
	h1->handleRequest(20);
	h1->handleRequest(3);
}

 

你可能感兴趣的:(c++)