意图:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系.将这些对象连成一条链,并沿着这条链传递请求,直到一个对象处理它为止.
适用性:
有多个对象可以处理一个请求,那个对象处理该请求运行时自动确定
你想在不明确制定接受者的情况下,向多个对象中的一个提交一个请求
可处理一个请求的对象集合应被动态指定
示例图:
示例代码:
class CHandler
{
public:
CHandler(CHandler*
nextHandler);
public:
~CHandler(void);
public:
void
HandleRequest(CRequest req)
{
if(IsMatch(req.GetRequestType()))
{
_HandleRequest(req);
}
else
{
if(m_NextHandler)
{
m_NextHandler->HandleRequest(req);
}
else
{
_tprintf(_T("unhandler
message/n"));
}
}
}
protected:
virtual void _HandleRequest(CRequest req) =0;
virtual bool IsMatch(CRequest::RequestType reqType)=0;
private:
CHandler* m_NextHandler;
};
//消息处理类处理消息
class CMessageHandler:public CHandler
{
public:
CMessageHandler(CHandler* pNextHandler)
:CHandler(pNextHandler)
{
}
public:
~CMessageHandler()
{
}
public:
virtual bool IsMatch(CRequest::RequestType
reqType)
{
if(reqType == CRequest::eMessage)
{
return true;
}
return false;
}
virtual void _HandleRequest(CRequest req)
{
_tprintf(_T("Message handled/n"));
}
};
//键盘处理类处理键盘消息
class CKeyHandler:public
CMessageHandler
{
public:
CKeyHandler(CHandler*
pNextHandler)
:CMessageHandler(pNextHandler)
{
}
public:
~CKeyHandler()
{
}
public:
virtual bool IsMatch(CRequest::RequestType reqType)
{
if(reqType == CRequest::eKey)
{
return
true;
}
return false;
}
virtual void
_HandleRequest(CRequest req)
{
_tprintf(_T("Key Message
handled/n"));
}
};
//处理请求
class CRequest
{
public:
enum RequestType
{
eMessage,
eKey,
eMouse,
};
public:
CRequest(CRequest::RequestType reqType);
public:
~CRequest(void);
public:
CRequest::RequestType
GetRequestType()
{
return m_ReqType;
}
private:
CRequest::RequestType m_ReqType;
};
//调用
CKeyHandler keyHandler(NULL);
CMessageHandler
messageHandler(&keyHandler);
CRequest keyReq(CRequest::eKey);
CRequest msgReq(CRequest::eMessage);
CRequest
mouseReq(CRequest::eMouse);
messageHandler.HandleRequest(keyReq);
messageHandler.HandleRequest(msgReq);
messageHandler.HandleRequest(mouseReq);