一、什么是链,链是一系列的节点的集合,链的各个节点可灵活拆分再重组。
二、何为责任链
责任链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理他为止。
下面这篇文章可以详细的讲述职责链模式的使用场景,职责链的优缺点,指责链的实例。
http://www.cnblogs.com/kym/archive/2009/04/06/1430078.html
hydra框架也支持责任链模式。使用的时候,只要继承ControlHandler类,然后就可以通过setSuccessor将对象链起来。然后除非重写handleControlEvent方法,否则就会将事件传递给责任链的下一个节点。
ControlHandler.h
/********************************************************************
Baina@copyright 2014
Author: mli
Date: 2014/10/21
---------------------------------------------------------------------
Remark:Define interfaces for handling ui event
As base class for any node in chain of responsibility
*********************************************************************/
#pragma once
#include "HydraDef.h"
namespace cocos2d{
class Ref;
}
NS_HYDRA_BEGIN
class ControlHandler
{
public:
void setSuccessor(ControlHandler *s){m_successor = s;}
virtual void handleControlEvent(cocos2d::Ref *pSender, const std::string &strMessageName,
const std::string &lParam = "", const std::string &wParam = "");
private:
ControlHandler *m_successor = nullptr;
};
NS_HYDRA_END
ControlHandler.cpp
#include "cocos2d.h"
#include "ControlHandler.h"
USING_NS_CC;
using namespace std;
NS_HYDRA_BEGIN
void ControlHandler::handleControlEvent(cocos2d::Ref *pSender, const std::string &strMessageName,
const std::string &lParam, const std::string &wParam)
{
if (m_successor)
{
m_successor->handleControlEvent(pSender, strMessageName, lParam, wParam);
}
}
NS_HYDRA_END
使用的时候,就通过调用handleControlEvent这个方法,开启责任的传递。知道找到一个合适的节点对相应的事件进行处理。