码迷,mamicode.com
首页 > 其他好文 > 详细

Chain of Responsibility模式

时间:2015-08-19 23:47:15      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:设计模式   designpattern   职责链模式   

消息传递是面向对象开发中经常用到的机制,例如异常的传递,如果当前函数/类无法处理异常,可以将其抛到上一层。消息传递类似,如果一个类收到消息,如果当前类无法处理,可以将消息按照预先定义好的路径传递下去,直到有类可以处理这个消息。这就是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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

Chain of Responsibility模式

标签:设计模式   designpattern   职责链模式   

原文地址:http://blog.csdn.net/kangroger/article/details/47789467

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!