设计模式之职责链模式(Chain of Responsibility)

职责链模式原理:

职责链模式和装饰模式以及组合模式类似的地方是都维持着指向父类的指针,

不同点是职责链模式每个子类都继承父类的指针及每个之类都维持着指向父类的指针,而组合模式与装饰模式是组合类鱼装饰类维持着指向父类的指针。

代码如下:

#include <iostream>
#include <string> using namespace std; class Manager
{
public:
Manager(string name,Manager* pmanager = NULL):m_name(name),m_pmanager(pmanager){}
virtual void dealSalary(string name,int num){}
protected:
Manager *m_pmanager;
string m_name;
}; class ComonManager:public Manager
{
public:
ComonManager(string name,Manager *pmanager):Manager(name,pmanager){}
virtual void dealSalary(string name,int num)
{
if (num < 300)
{
cout << "经理"<<m_name<<"批准了"<<name<<num<<"元的工资"<<endl;
}
else
{
m_pmanager->dealSalary(name,num);
}
}
}; class MidManager:public Manager
{
public:
MidManager(string name,Manager *pmanager):Manager(name,pmanager){}
virtual void dealSalary(string name,int num)
{
if (num < 500)
{
cout << "总监"<<m_name<<"批准了"<<name<<num<<"元的工资"<<endl;
}
else
{
m_pmanager->dealSalary(name,num);
}
}
}; class GeneralManager:public Manager
{
public:
GeneralManager(string name,Manager *pmanager):Manager(name,pmanager){}
virtual void dealSalary(string name,int num)
{
cout << "总经理"<<m_name<<"批准了"<<name<<num<<"元的工资"<<endl;
}
}; int main()
{
Manager* pgeneral = new GeneralManager("A",NULL);
Manager* pmiddle = new MidManager("B",pgeneral);
Manager* pcommon = new ComonManager("C",pmiddle);
pcommon->dealSalary("D",200);
pcommon->dealSalary("E",400);
pcommon->dealSalary("F",1000);
return 0;
}
上一篇:bzoj 1305: [CQOI2009]dance跳舞


下一篇:BZOJ 3597 SCOI2014 方伯伯送椰子 网络流分析+SPFA