職責鏈模式,用我的理解就是動作的處理鏈表。根據請求的不同類型,在鏈表查找相應類型的處理者。處理者是一個鏈表。
用下面的一個圖來解釋
基本的UML圖爲
- // ChainofResponsibility.cpp : 定義控制檯應用程序的入口點。
- //************************************************************************/
- /* @filename ChainofResponsibility.cpp
- @author wallwind
- @createtime 2012/11/6 11:58
- @function 責任鏈模式
- @email [email protected]
- @weibo @成林有理想
- */
- /************************************************************************/
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- class IChain
- {
- public:
- IChain():m_nextChain(NULL)
- {
- }
- virtual ~IChain()
- {
- if (m_nextChain !=NULL)
- {
- delete m_nextChain;
- m_nextChain = NULL;
- }
- }
- void setChainHandler(IChain* handler)
- {
- m_nextChain = handler;
- }
- virtual void handleReq(int reqtype) = 0;
- protected:
- IChain* m_nextChain;
- };
- class FirstHandler:public IChain
- {
- public:
- FirstHandler():IChain()
- {
- }
- virtual ~FirstHandler(){}
- virtual void handleReq(int reqtype)
- {
- if (reqtype <3)
- {
- cout<<"FirstHandler::handleReq"<<endl;
- }
- else if (m_nextChain !=NULL)
- {
- m_nextChain->handleReq(reqtype);
- }
- else
- {
- cout<<"no handler"<<endl;
- }
- }
- };
- class SecondHandler:public IChain
- {
- public:
- SecondHandler():IChain()
- {
- }
- virtual ~SecondHandler(){}
- virtual void handleReq(int reqtype)
- {
- if (reqtype <7)
- {
- cout<<"SecondHandler::handleReq"<<endl;
- }
- else if (m_nextChain !=NULL)
- {
- m_nextChain->handleReq(reqtype);
- }
- else
- {
- cout<<"no handler"<<endl;
- }
- }
- };
- class ThirdHandler:public IChain
- {
- public:
- ThirdHandler():IChain()
- {
- }
- virtual ~ThirdHandler(){}
- virtual void handleReq(int reqtype)
- {
- if (reqtype <9)
- {
- cout<<"ThirdHandler::handleReq"<<endl;
- }
- else if (m_nextChain !=NULL)
- {
- m_nextChain->handleReq(reqtype);
- }
- else
- {
- cout<<"no handler"<<endl;
- }
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- IChain *p1handler= new FirstHandler;
- IChain *p2handler= new SecondHandler;
- IChain *p3handler= new ThirdHandler;
- p1handler ->setChainHandler(p2handler);
- p2handler->setChainHandler(p3handler);
- p3handler ->handleReq(4);
- delete p1handler,p2handler,p3handler;
- return 0;
- }