首页 > 代码库 > 职责链模式之C++实现
职责链模式之C++实现
#include "stdafx.h"
#include <iostream>
using namespace std;
class Programmer
{
protected:
Programmer *next;
public:
void SetNext(Programmer *programmer)
{
next = programmer;
}
virtual void ProcessErrorCode(int error) = 0;
};
class ProgrammerA : public Programmer
{
public:
void ProcessErrorCode(int error)
{
if (error >= 0 && error < 10)
{
cout << "Error(" << error << "): 错误出现在ProgrammerA的代码" << endl;
}
else
{
next->ProcessErrorCode(error);
}
}
};
class ProgrammerB : public Programmer
{
public:
void ProcessErrorCode(int error)
{
if (error >= 10 && error < 20)
{
cout << "Error(" << error << "): 错误出现在ProgrammerB的代码" << endl;
}
else
{
next->ProcessErrorCode(error);
}
}
};
class ProgrammerC : public Programmer
{
public:
void ProcessErrorCode(int error)
{
if (error >= 20 && error < 30)
{
cout << "Error(" << error << "): 错误出现在ProgrammerC的代码" << endl;
}
else
{
cout << "Error(" << error << "): 异常:未知错误码" << endl;
}
}
};
int main(void)
{
Programmer *pProgrammerA = new ProgrammerA;
Programmer *pProgrammerB = new ProgrammerB;
Programmer *pProgrammerC = new ProgrammerC;
pProgrammerA->SetNext(pProgrammerB);
pProgrammerB->SetNext(pProgrammerC);
int izError[5] = {5, 6, 18, 23, 45};
cout << "======== 根据错误码定位bug出现的代码段 ========" << endl;
for (int i = 0; i < 5; i++)
{
pProgrammerA->ProcessErrorCode(izError[i]);
}
return 0;
#include <iostream>
using namespace std;
class Programmer
{
protected:
Programmer *next;
public:
void SetNext(Programmer *programmer)
{
next = programmer;
}
virtual void ProcessErrorCode(int error) = 0;
};
class ProgrammerA : public Programmer
{
public:
void ProcessErrorCode(int error)
{
if (error >= 0 && error < 10)
{
cout << "Error(" << error << "): 错误出现在ProgrammerA的代码" << endl;
}
else
{
next->ProcessErrorCode(error);
}
}
};
class ProgrammerB : public Programmer
{
public:
void ProcessErrorCode(int error)
{
if (error >= 10 && error < 20)
{
cout << "Error(" << error << "): 错误出现在ProgrammerB的代码" << endl;
}
else
{
next->ProcessErrorCode(error);
}
}
};
class ProgrammerC : public Programmer
{
public:
void ProcessErrorCode(int error)
{
if (error >= 20 && error < 30)
{
cout << "Error(" << error << "): 错误出现在ProgrammerC的代码" << endl;
}
else
{
cout << "Error(" << error << "): 异常:未知错误码" << endl;
}
}
};
int main(void)
{
Programmer *pProgrammerA = new ProgrammerA;
Programmer *pProgrammerB = new ProgrammerB;
Programmer *pProgrammerC = new ProgrammerC;
pProgrammerA->SetNext(pProgrammerB);
pProgrammerB->SetNext(pProgrammerC);
int izError[5] = {5, 6, 18, 23, 45};
cout << "======== 根据错误码定位bug出现的代码段 ========" << endl;
for (int i = 0; i < 5; i++)
{
pProgrammerA->ProcessErrorCode(izError[i]);
}
return 0;
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。