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

职责链模式是一种设计模式,允许将多个对象串联成一个处理请求的链,请求沿着链传递,直到某个对象处理它。此模式降低了发送者与接受者间的耦合。示例代码展示了如何创建一个处理不同类型请求的职责链,包括Handle1、Handle2和Handle3,它们根据请求类型决定是否处理请求。在实际应用中,这种模式适用于请求有多个潜在处理者的场景。
摘要由CSDN通过智能技术生成

职责链模式

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

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

#include<iostream>
#include<string>
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;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dailingGuo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值