简介

责任链模式,使责任链上的每个对象都有机会处理请求,避免请求的发送者和接收者耦合在一起。将接收对象链接起来,把请求沿着这条链传递,直到有对象可以处理它。

UML类图

clipboard.png

示例

现在出了事故,政府一般使用问责的方法。如果事情太大,最高领导人都要亲自批示。如果事情很小,直接责任人就可以handle它了。
责任链上相关类,responsibilitychain.h

#ifndef RESPONSIBILITY_H
#define RESPONSIBILITY_H
#include <iostream>
#include <string>

using namespace std;
enum{low, middle, high} Level;
class CResponsor
{
public:
    CResponsor(){m_pResponsor = NULL;};
    void SetResponsor(CResponsor* pResponsor)
    {
        m_pResponsor = pResponsor;
    }
    virtual void HandleRequest(const int& nLevel, const string& strContent) = 0;
protected:
    CResponsor* m_pResponsor;
};

class CCityResponsor:public CResponsor
{
public:
    void HandleRequest(const int& nLevel, const string& strContent)
    {
        if(nLevel == low)
            cout<<"City response:"<<strContent;
        else
            m_pResponsor->HandleRequest(nLevel, strContent);
    }
};

class CProvinceResponsor:public CResponsor
{
public:
    void HandleRequest(const int& nLevel, const string& strContent)
    {
        if(nLevel == middle)
            cout<<"Province response:"<<strContent;
        else
            m_pResponsor->HandleRequest(nLevel, strContent);
    }
};

class CStateResponsor:public CResponsor
{
public:
    void HandleRequest(const int& nLevel, const string& strContent)
    {
        cout<<"State response:"<<strContent;
    }
};

#endif

客户端调用,main.cpp

#include "responsibilitychain.h"

#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}
int main(int argc, char* argv[])
{
    CResponsor* pStateResponsor = new CStateResponsor;
    CResponsor* pProvinceResponsor = new CProvinceResponsor();
    CResponsor* pCityResponsor = new CCityResponsor();
    pCityResponsor->SetResponsor(pProvinceResponsor);
    pProvinceResponsor->SetResponsor(pStateResponsor);

    pCityResponsor->HandleRequest(high, "Fire happened.");
    SAFE_DELETE(pCityResponsor);
    SAFE_DELETE(pProvinceResponsor);
    SAFE_DELETE(pStateResponsor);
    return 0;
}

one_piece
26 声望8 粉丝

« 上一篇
代理模式
下一篇 »
命令模式