责任链模式(Chain of Responsibility)的目标是使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递请求,直到有一个对象处理它为止。结构图为:
用一个采购的例子来说明,采购人员在进行采购前需经过上级部门的批准,对于不同金额的采购分别要由不同级别的上级才能审批,假设1万以内的采购需要主管批准,10万以内的需要主管向总经理申请批准,超过10万总经理向需董事长宴请批准,这时对于采购的审批过程就形成了一条责任链,对于不同的采购请求就需要一级一级的向上传递,并最终传递到最上级然后自行处理。
结构图如下:
实现代码:
//Processor.h
class Processor
{
public:
virtual ~Processor();
virtual void Request(double) = 0;
void SetSuccessor(Processor*);
protected:
Processor();
Processor* m_pProcessor;
};
//Processor.cpp
#include "stdafx.h"
#include "Processor.h"
Processor::Processor()
{
}
Processor::~Processor()
{
if(m_pProcessor != NULL)
{
delete m_pProcessor;
m_pProcessor = NULL;
}
}
void Processor::SetSuccessor(Processor* pProcessor)
{
m_pProcessor = pProcessor;
}
//Director.h
#include "Processor.h"
class Director : public Processor
{
public:
Director();
virtual ~Director();
void Request(double);
};
//Director.cpp
#include "stdafx.h"
#include "Director.h"
#include <iostream>
using namespace std;
Director::Director()
{
}
Director::~Director()
{
}
void Director::Request(double dAmount)
{
if(dAmount <= 10000)
{
cout << "主管审批了采购请求" << endl;
}
else
{
cout << "申请金额走出主管权限范围,需向总经理申请审批" << endl;
if(this->m_pProcessor != NULL)
{
m_pProcessor->Request(dAmount);
}
}
}
//Manager.h
#include "Processor.h"
class Manager : public Processor
{
public:
Manager();
virtual ~Manager();
void Request(double);
};
//Manager.cpp
#include "stdafx.h"
#include "Manager.h"
#include <iostream>
using namespace std;
Manager::Manager()
{
}
Manager::~Manager()
{
}
void Manager::Request(double dAmount)
{
if(dAmount <= 100000)
{
cout << "总经理审批了采购请求" << endl;
}
else
{
cout << "申请金额超出总经理权限范围,需向董事长申请审批" << endl;
if(this->m_pProcessor != NULL)
{
m_pProcessor->Request(dAmount);
}
}
}
//Chariman.h
#include "Processor.h"
class Chariman : public Processor
{
public:
Chariman();
virtual ~Chariman();
void Request(double);
};
//Chariman.cpp
#include "stdafx.h"
#include "Chariman.h"
#include <iostream>
using namespace std;
Chariman::Chariman()
{
}
Chariman::~Chariman()
{
}
void Chariman::Request(double dAmount)
{
cout << "董事长审批了采购请求" << endl;
}
//main.cpp
#include "stdafx.h"
#include "Processor.h"
#include "Director.h"
#include "Manager.h"
#include "Chariman.h"
int main(int argc, char* argv[])
{
Processor* pDirector = new Director;
Processor* pManager = new Manager;
Processor* pChariman = new Chariman;
pDirector->SetSuccessor(pManager);
pManager->SetSuccessor(pChariman);
pDirector->Request(10000000.00);
return 0;
}
代码中申请了超过10成的订购请求,于是各级别负责人一步一步向上级提交申请,并最终由最上层决定审批结果。
运行结果如下:
申请金额超出主管权限范围,需向总经理申请审批
申请金额超出总经理权限范围,需向董事长申请审批
董事长审批了采购请求