C++:责任链模式实例

/ 编程思想C++ / 没有评论 / 1871浏览
#include <iostream>
#include <string>
#include <memory>

enum class TYPE
{
	REQ1,
	REQ2,
	REQ3
};

class request
{
public:
	request(const std::string& msg, TYPE type):m_sMsg(msg),t(type)
	{

	}
	~request()
	{

	}

	TYPE getType() const
	{
		return t;
	}

private:
	std::string m_sMsg;
	TYPE t;
};

class chainHanlder
{
public:
	chainHanlder()
	{

	}
	virtual ~chainHanlder()
	{

	}

	void setNextHandle(const std::shared_ptr<chainHanlder> &p)
	{
		m_pNext = p;
	}

	void handle(const request& q)
	{
		if (can(q))
		{
			process(q);
		}
		else
		{
			nextChainProcess(q);
		}
	}
protected:
	virtual bool can(const request& q) = 0;
	virtual void process(const request& q) = 0;

private:
	void nextChainProcess(const request& q)
	{
		if (m_pNext)
		{
			m_pNext->process(q);
		}
	}

private:
	std::shared_ptr<chainHanlder> m_pNext;
};

class Handle1 : public chainHanlder
{
protected:
	virtual bool can(const request& q)
	{
		return q.getType() == TYPE::REQ1;
	}
	virtual void process(const request& q)
	{
		std::cout << "handle1" << std::endl;
	}
};

class Handle2 : public chainHanlder
{
protected:
	virtual bool can(const request& q)
	{
		return q.getType() == TYPE::REQ2;
	}
	virtual void process(const request& q)
	{
		std::cout << "Handle2" << std::endl;
	}
};
int main()
{
	std::shared_ptr<Handle1> h1 = std::make_shared<Handle1>();
	std::shared_ptr<Handle2> h2 = std::make_shared<Handle2>();
	h1->setNextHandle(h2);


	request q("aa", TYPE::REQ2);
	h1->handle(q);

	return 0;
}