职责连模式简单实现

设计模式目录
职责连模式简单实现_第1张图片
https://blog.csdn.net/xie__jin__cheng/article/details/87871576(状态,职责链,策略对比分析)
几种模式的对比分析
职责链:就是处理问题的类有一个处理问题的级别,问题(函数调用)都先发给低级别的类,如果解决不了,就向上级类传递。
代码(c++)

#include 
#include 

using namespace std;

//
// ---------------------------------抽象层------------------------------
//
class DeBug;
class Handler 
{
protected:
	Handler* m_pHandler;	
public:
	virtual void HandleRequest(DeBug& bug){}
};

//
// ------------------------------实施层----------------------------------
//
class DeBug
{
public:
	int rank;
};

class ConcreteHandler1:public Handler
{
public:
	ConcreteHandler1(Handler* h)
	{
		m_pHandler = h;
	}
	void HandleRequest(DeBug& bug)
	{
		if(bug.rank<2)
		{
			cout<<"程序员:轻松搞定 \n";
		}
		else
		{
			cout<<"程序员:我搞不定,交给组长 \n";
			m_pHandler->HandleRequest(bug);
		}
	}	
};

class ConcreteHandler2:public Handler
{
public:
	ConcreteHandler2(Handler* h)
	{
		m_pHandler = h;
	}
	void HandleRequest(DeBug& bug)
	{
		if(bug.rank<2)
		{
			cout<<"组长:有点麻烦 搞定 \n";
		}
		else
		{
			cout<<"组长:我搞不定,交给经理 \n";
			m_pHandler->HandleRequest(bug);
		}
	}
};
class ConcreteHandler3:public Handler
{
public:
	void HandleRequest(DeBug& bug)
	{
		cout<<"经路:啥都搞定 \n";	
	}
};

//
// 客户端(调用层)
//
int main()
{
	ConcreteHandler3* jing_li = new ConcreteHandler3();
	ConcreteHandler2* zhu_zhang = new ConcreteHandler2(jing_li);
	ConcreteHandler1* kai_fu = new ConcreteHandler1(zhu_zhang);

	DeBug bg;
	bg.rank = 2;
	kai_fu->HandleRequest(bg);

	int a;
	cin>>a;
	return 0;
}

你可能感兴趣的:(设计模式,职责链,简单,容易)