责任链模式,模拟请假的审批流程,主管批准小于等于3天的,经理批准小于七天的,总经理批准大于等于7天。
chain.h
#include <string>
typedef struct LeaveReq
{
std::string moName;
int miNumOfDays;
}LeaveReq;
class CHandler
{
public:
CHandler(std::string aoName): moName(aoName){}
virtual ~CHandler(){}
void SetNextHandler(CHandler* aoNextHandler)
{
moNextHandler = aoNextHandler;
}
virtual bool Process(const LeaveReq& aoReq) = 0;
protected:
CHandler* moNextHandler;
std::string moName;
};
class CDirector : public CHandler
{
public:
CDirector(std::string aoName):CHandler(aoName)
{
}
virtual ~CDirector(){}
bool Process(const LeaveReq& aoReq);
};
class CManager : public CHandler
{
public:
CManager(std::string aoName):CHandler(aoName)
{
}
virtual ~CManager(){}
bool Process(const LeaveReq& aoReq);
};
class CTopManager : public CHandler
{
public:
CTopManager(std::string aoName):CHandler(aoName)
{
}
virtual ~CTopManager(){}
bool Process(const LeaveReq& aoReq);
};
chain.cpp
#include "chain.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int Random()
{
srand((unsigned)time(0));
return rand() % 20;
}
bool CDirector::Process(const LeaveReq& aoReq)
{
if (aoReq.miNumOfDays <= 3)
{
int liCnt = Random();
printf("rand num is %d\n", liCnt);
if (liCnt <= 3)
{
printf("批准\n");
return true;
}
printf("不批准\n");
return false;
}
return moNextHandler->Process(aoReq);
}
bool CManager::Process(const LeaveReq& aoReq)
{
if (aoReq.miNumOfDays < 7)
{
int liCnt = Random();
printf("rand num is %d\n", liCnt);
if (liCnt < 7)
{
printf("批准\n");
return true;
}
printf("不批准\n");
return false;
}
return moNextHandler->Process(aoReq);
}
bool CTopManager::Process(const LeaveReq& aoReq)
{
if (aoReq.miNumOfDays >= 7)
{
int liCnt = Random();
printf("rand num is %d\n", liCnt);
if (liCnt >= 7)
{
printf("批准\n");
return true;
}
printf("不批准\n");
return false;
}
return false;
}
test.cpp
#include "chain.h"
int main(int argv, char* argc[])
{
CDirector* lpoDir = new CDirector("主管");
CManager* lpoMan = new CManager("经理");
CTopManager* lpoTop = new CTopManager("总经理");
lpoDir->SetNextHandler(lpoMan);
lpoMan->SetNextHandler(lpoTop);
LeaveReq loReq1;
loReq1.moName = "zhangsan";
loReq1.miNumOfDays = 2;
lpoDir->Process(loReq1);
LeaveReq loReq2;
loReq2.moName = "lisi";
loReq2.miNumOfDays = 5;
lpoDir->Process(loReq2);
LeaveReq loReq3;
loReq3.moName = "wangwu";
loReq3.miNumOfDays = 15;
lpoDir->Process(loReq3);
delete lpoTop;
delete lpoMan;
delete lpoDir;
return 0;
}