使多個對象都有機會處理請求,從而避免請求的發(fā)送者和接收者之間的耦合關(guān)系,將這些對象連成一條鏈,并沿著這條鏈傳遞請求,直到有一個對象處理它為止
UML圖:
適用:
有多個的對象可以處理一個請求,哪個對象處理該請求運行時刻自動確定
你想在不明確指定接收者的情況下,向多個對象匯總的一個提交請求
可處理一個請求的對象結(jié)合應(yīng)被動態(tài)指定
//test.h
//////////////////////////////////////////////////////////////////////////
class Handler
{
public:
Handler(Handler *pSuccessor = NULL);
virtual ~Handler();
virtual void HandlerRequest() = 0;
protected:
Handler* m_pSuccessor;
};
class ConCreateHandle1 : public Handler
{
public:
ConCreateHandle1(Handler *pSuccessor = NULL) : Handler(pSuccessor){}
virtual ~ConCreateHandle1(){}
virtual void HandlerRequest();
};
class ConCreateHandle2 : public Handler
{
public:
ConCreateHandle2(Handler *pSuccessor = NULL) : Handler(pSuccessor){}
virtual ~ConCreateHandle2(){}
virtual void HandlerRequest();
};
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include "test.h"
using namespace std;
//////////////////////////////////////////////////////////////////////////
Handler::Handler(Handler *pSuccessor /* = NULL */) : m_pSuccessor(pSuccessor)
{
}
Handler::~Handler()
{
delete m_pSuccessor;
m_pSuccessor = NULL;
}
void ConCreateHandle1::HandlerRequest()
{
if (NULL != m_pSuccessor)
{
m_pSuccessor->HandlerRequest();
}
else
{
cout << "HandlerRequest by ConCreateHandle1\n";
}
}
void ConCreateHandle2::HandlerRequest()
{
// 如果m_pSuccessor被初始化了就調(diào)用他的接口,負責(zé)調(diào)用自己的接口
if (NULL != m_pSuccessor)
{
m_pSuccessor->HandlerRequest();
}
else
{
cout << "HandlerRequest by ConCreateHandle2\n";
}
}
//////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
Handler *p1 = new ConCreateHandle1;
Handler *p2 = new ConCreateHandle2(p1);
p2->HandlerRequest();
delete p2;
system("pause");
return 0;
}


