消息传递是面向对象开发中经常用到的机制,例如异常的传递,如果当前函数/类无法处理异常,可以将其抛到上一层。消息传递类似,如果一个类收到消息,如果当前类无法处理,可以将消息按照预先定义好的路径传递下去,直到有类可以处理这个消息。这就是Chain of Responsibility模式。
Handle类中持有自己的指针/引用,指向某一个派生类。如果当前类无法处理消息,则调用派生类来处理。
实现:
Handle.h
#ifndef _HANDLE_H_
#define _HANDLE_H_
class Handle
{
public:
virtual ~Handle();
virtual void HandleRequest() = 0;
void SetSuccessor(Handle* succ);
Handle* GetSuccessor();
protected:
Handle();
Handle(Handle* succ);
private:
Handle* succ_;
};
class ConcreteHandleA :public Handle
{
public:
ConcreteHandleA();
ConcreteHandleA(Handle* succ);
~ConcreteHandleA();
void HandleRequest();
};
class ConcreteHandleB :public Handle
{
public:
ConcreteHandleB();
ConcreteHandleB(Handle* succ);
~ConcreteHandleB();
void HandleRequest();
};
#endif
Handle.cpp
#include "Handle.h"
#include <iostream>
Handle::Handle()
{
succ_ = NULL;
}
Handle::Handle(Handle* succ)
{
succ_ = succ;
}
Handle::~Handle()
{
if (succ_)
delete succ_;
}
void Handle::SetSuccessor(Handle* succ)
{
succ_ = succ;
}
Handle* Handle::GetSuccessor()
{
return succ_;
}
void Handle::HandleRequest()
{}
ConcreteHandleA::ConcreteHandleA()
{}
ConcreteHandleA::ConcreteHandleA(Handle* succ) :Handle(succ)
{}
ConcreteHandleA::~ConcreteHandleA()
{}
void ConcreteHandleA::HandleRequest()
{
Handle* succ = GetSuccessor();
if (succ)
{
std::cout << "ConcreteHandleA 我把处理权交给后继节点……" << std::endl;
succ->HandleRequest();
}
else
{
std::cout << "ConcreteHandleA 我没有后继结点,我必须自己处理……" << std::endl;
}
}
ConcreteHandleB::ConcreteHandleB()
{}
ConcreteHandleB::ConcreteHandleB(Handle* succ) :Handle(succ)
{}
ConcreteHandleB::~ConcreteHandleB()
{}
void ConcreteHandleB::HandleRequest()
{
Handle* succ = GetSuccessor();
if (succ)
{
std::cout << "ConcreteHandleB 我把处理权交给后继节点……" << std::endl;
succ->HandleRequest();
}
else
{
std::cout << "ConcreteHandleB 我没有后继结点,我必须自己处理……" << std::endl;
}
}
main.cpp
#include "Handle.h"
#include <iostream>
int main()
{
Handle* h1 = new ConcreteHandleA();
Handle* h2 = new ConcreteHandleB();
h1->SetSuccessor(h2);
h1->HandleRequest();
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/kangroger/article/details/47789467