设计模式读书笔记:Chain of Responsibility(责任链)
2015-07-10 17:30:18
意图:
使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
结构图:来自 《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/ChainOfResponsibility
Handle
namespace NS_CHAINOFRESPONSIBILITY {
class Handle {
public:
Handle(Handle *successor) : _successor(successor) {}
virtual ~Handle() {}
virtual void HandleRequest(int request) = 0;
Handle *getSuccessor(void) { return _successor; }
private:
Handle *_successor;
};
} /* namespace NS_CHAINOFRESPONSIBILITY */
ConcreteHandle1
#include <iostream>
#include "Handle.h"
namespace NS_CHAINOFRESPONSIBILITY {
class ConcreteHandle1 : public Handle
{
public:
ConcreteHandle1(Handle *successor) : Handle(successor) {}
virtual ~ConcreteHandle1() {}
virtual void HandleRequest(int request)
{
std::cout << "HandleRequest: " << request << std::endl;
}
};
} /* namespace NS_CHAINOFRESPONSIBILITY */
ConcreteHandle2
#include <iostream>
#include "Handle.h"
namespace NS_CHAINOFRESPONSIBILITY {
class ConcreteHandle2 : public Handle
{
public:
ConcreteHandle2(Handle *successor) : Handle(successor) {}
virtual ~ConcreteHandle2() {}
virtual void HandleRequest(int request)
{
if (request == 100)
{
std::cout << "Handle 100 Request." << std::endl;
}
else
{
if (getSuccessor())
getSuccessor()->HandleRequest(request);
}
}
};
} /* namespace NS_CHAINOFRESPONSIBILITY */
main
#include "ChainOfResponsibility/ConcreteHandle1.h"
#include "ChainOfResponsibility/ConcreteHandle2.h"
using namespace NS_CHAINOFRESPONSIBILITY;
int main(void)
{
ConcreteHandle1 ch1(0);
ConcreteHandle2 ch2(&ch1);
ch2.HandleRequest(100);
ch2.HandleRequest(0);
}
附加: