19_设计模式之职责链模式

模式定义:

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。

使用动机:

软件构建过程中,一个请求可能被多个对象处理,但是每个请求在运行时只能有一个接受者,如果显示指定,将必不可少的带来请求发送者与接受者的紧耦合。

enum RequestType
{
	REQ_HANDLER1,
	REQ_HANDLER2,
	REQ_HANDLER3
};

class Request
{
private:
	string m_desc;
	RequestType m_reqType;

public:
	Request(const string &desc, const RequestType &reqType) : m_desc(desc), m_reqType(reqType) { }

	string getDesc() const { return m_desc; }
	RequestType getReqType() const { return m_reqType;  }
};

class ChainHandler
{
public:
	ChainHandler *m_pNextChainHandler;
	void sendRequestToNextHandler(const Request &req)
	{
		if (m_pNextChainHandler != nullptr)
		{
			m_pNextChainHandler->handle(req);
		}
	}
protected:
	virtual bool canHandleRequest(const Request &req) = 0;
	virtual void processRequest(const Request &req) = 0;

public:
	ChainHandler() : m_pNextChainHandler(nullptr) { }
	void setNextChain(ChainHandler *pNext)
	{
		m_pNextChainHandler = pNext;
	}
	void handle(const Request &req)
	{
		if (canHandleRequest(req))
		{
			processRequest(req);
		}
		else
		{
			sendRequestToNextHandler(req);
		}
	}
};

class Handler1 : public ChainHandler
{
protected:
	bool canHandleRequest(const Request &req) override
	{
		return req.getReqType() == RequestType::REQ_HANDLER1;
	}
	void processRequest(const Request &req) override
	{

	}
};

class Handler2 : public ChainHandler
{
protected:
	bool canHandleRequest(const Request &req) override
	{
		return req.getReqType() == RequestType::REQ_HANDLER2;
	}
	void processRequest(const Request &req) override { }
};

class Handler3 : public ChainHandler
{
protected:
	bool canHandleRequest(const Request &req) override
	{
		return req.getReqType() == RequestType::REQ_HANDLER3;
	}
	void processRequest(const Request &req) override { }
};

int main(array<System::String ^> ^args)
{
	Handler1 h1;
	Handler2 h2;
	Handler3 h3;

	h1.setNextChain(&h2);
	h2.setNextChain(&h3);

	Request req("test", RequestType::REQ_HANDLER3);
	h1.handle(req);

	return 0;
}

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页