设计模式-Chain of Responsibility (行为模式) 降低系统的耦合性

//以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码

//Handle.h

#pragma once

class Handle
{
public:
    virtual ~Handle();
    virtual void HandleRequest() = 0;
    void SetSuccessor(Handle* succ);
    Handle* GetSuccessor();
protected:
    Handle();
    Handle(Handle* succ);
private:
    Handle* _succ;
};

class ConcreateHandleA :public Handle
{
public:
    ConcreateHandleA();
    ~ConcreateHandleA();
    ConcreateHandleA(Handle* succ);
    void HandleRequest();
protected:
private:
};

class ConcreateHandleB :public Handle
{
public:
    ConcreateHandleB();
    ~ConcreateHandleB();
    ConcreateHandleB(Handle* succ);
    void HandleRequest();
protected:
private:
};

//Handle.cpp

#include"Handle.h"
#include<iostream>

Handle::Handle()
{
    _succ = 0;
}
Handle::Handle(Handle* succ)
{
    this->_succ = succ;
}
Handle::~Handle()
{
    delete _succ;
}

void Handle::SetSuccessor(Handle* succ)
{
    _succ = succ;
}
Handle* Handle::GetSuccessor()
{
    return _succ;
}
void Handle::HandleRequest(){}

ConcreateHandleA::ConcreateHandleA(){}
ConcreateHandleA::~ConcreateHandleA(){}
ConcreateHandleA::ConcreateHandleA(Handle* succ) :Handle(succ){}

void ConcreateHandleA::HandleRequest()
{
    if (this->GetSuccessor() != 0)
    {
        std::cout << "ConcreteHandleA 将处理权交给后继节点...." << std::endl;
        this->GetSuccessor()->HandleRequest();
    }
    else
    {
        std::cout << "ConcreteHandleA没有后继了,必须自己处理..." << std::endl;
    }
}


ConcreateHandleB::ConcreateHandleB(){}
ConcreateHandleB::~ConcreateHandleB(){}
ConcreateHandleB::ConcreateHandleB(Handle* succ) :Handle(succ){}

void ConcreateHandleB::HandleRequest()
{
    if (this->GetSuccessor() != 0)
    {
        std::cout << "ConcreteHandleB 将处理权交给后继节点..." << std::endl;
        this->GetSuccessor()->HandleRequest();
    }
    else
    {
        std::cout << "ConcreteHandleB 没有后继了,必须自己处理..." << std::endl;
    }
}

//main.cpp

#include"Handle.h"
#include<iostream>
#include<string>

int main(int args, char* argv)
{
    Handle* h1 = new ConcreateHandleA();
    Handle* h2 = new ConcreateHandleB();
    h1->SetSuccessor(h2);
    h1->HandleRequest();
    getchar();
    return 0;
}
posted @ 2019-12-24 10:05  fourmii  阅读(336)  评论(0编辑  收藏  举报