C++设计模式——职责链模式(chain of Responsibility)

职责链模式

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

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

#include
#include
using namespace std;

enum class RequestType
{
	REQ_HANDLE1,
	REQ_HANDLE2,
	REQ_HANDLE3,
};
//请求的消息体
class Request {
private:
	string description;
	RequestType reqType;
public:
	Request(const string& str,RequestType type):description(str),reqType(type){}
	RequestType getReqType() const { return reqType; }
	const string& getDescription() const { return description; }
};


class ChainHandle {
private:
	ChainHandle* nextChain;
	void sendReqToNextHandle(const Request& req) {
		if (nextChain != nullptr)
			nextChain->handle(req);
	}
protected:
	virtual bool canHandleReq(const Request& req) = 0;
	virtual void processRequest(const Request& req) = 0;
public:
	ChainHandle():nextChain(nullptr){}
	//每个职责类似链表的形式串联起来
	void setNextChain(ChainHandle* next) {
		nextChain = next;
	}
	void handle(const Request& req) {
		if (canHandleReq(req))
			processRequest(req);
		else
			sendReqToNextHandle(req);
	}
};

class Handle1 :public ChainHandle {
protected:
	bool canHandleReq(const Request& req) override {
		return req.getReqType() == RequestType::REQ_HANDLE1;
	}
	void processRequest(const Request& req) override {
		cout << "Handle1 is hanle Request: " << req.getDescription() << endl;
	}
};

class Handle2 :public ChainHandle {
protected:
	bool canHandleReq(const Request& req) override {
		return req.getReqType() == RequestType::REQ_HANDLE2;
	}
	void processRequest(const Request& req) override {
		cout << "Handle2 is hanle Request: " << req.getDescription() << endl;
	}
};
class Handle3 :public ChainHandle {
protected:
	bool canHandleReq(const Request& req) override {
		return req.getReqType() == RequestType::REQ_HANDLE3;
	}
	void processRequest(const Request& req) override {
		cout << "Handle3 is hanle Request: " << req.getDescription() << endl;
	}
};

int main()
{
	Request* req = new Request(" proecss request:   ", RequestType::REQ_HANDLE3);
	ChainHandle* chain1 = new Handle1();
	ChainHandle* chain2 = new Handle2();
	ChainHandle* chain3 = new Handle3();
	//将每个职责类串联成一个链条
	chain1->setNextChain(chain2);
	chain2->setNextChain(chain3);
	//执行该职责链
	chain1->handle(*req);
	delete req, chain1, chain2, chain3;
	return 0;
}

测试结果如下:
在这里插入图片描述
职责链模式适用于:一个请求有多个接受者,但是最后的执行者只是其中某一个接受者。

你可能感兴趣的:(C++设计模式,c++,设计模式)