设计模式——责任链模式_Chain of Responsibility Pattern

责任链模式:

Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.(使多个对象都有机会处理请求,从而避免了请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链条传递该请求,直到有对象处理它为止


C++实现:

#ifndef __CHAIN_OF_RESPONSIBILTY_H__
#define __CHAIN_OF_RESPONSIBILTY_H__

#include <iostream>
using namespace std;

class ChainHandle {
public:
	ChainHandle() : _succ(0) { }
	virtual ~ChainHandle() { delete _succ; }
	virtual void HandleRequest() = 0;
	void SetSuccessor(ChainHandle* pSucc) { _succ = pSucc; }
	ChainHandle* GetHandle() { return _succ; }

private:
	ChainHandle* _succ;
};

class ConcreteHandleA : public ChainHandle {
public:
	void HandleRequest() {
		if (this->GetHandle() != NULL) {
			cout << "ConcreteHandleA 把责任转交给后继结点处理" << endl;
			this->GetHandle()->HandleRequest();
		} else {
			cout << "ConcreteHandleA 没有后继,必须自己处理" << endl;
		}
	}
};

class ConcreteHandleB : public ChainHandle {
public:
	void HandleRequest() {
		if (this->GetHandle() != NULL) {
			cout << "ConcreteHandleB 把责任转交给后继结点处理" << endl;
			this->GetHandle()->HandleRequest();
		} else {
			cout << "ConcreteHandleB 没有后继,必须自己处理" << endl;
		}
	}
};

#endif


#include "ChainOfResponsibility.h"


int main()
{
	ChainHandle* h1 = new ConcreteHandleA();
	ChainHandle* h2 = new ConcreteHandleB();
	h1->SetSuccessor(h2);
	h1->HandleRequest();

	return 0;
}

Chain of Responsibility 模式的最大的优点就是给系统降低了耦合性,请求的发送者完全不必知道该请求会被哪个应答对象处理,极大地降低了系统的耦合性。 

缺点:1,性能问题:每次都是从链头遍历。2,调试困难,当环节较多的时候,调试的逻辑变得复杂。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值