题目:
假设有个呼叫中心,有接线员、经理、主管三种角色。如果接线员无法处理呼叫,就上传给经理;如果仍无法处理,则上传给主管。请用代码描述这一过程。
分析:
典型的职责链设计模式的题目,今天第一次练习,该题目可以大概设计成两个类:
- 打电话的客户类(初步设计为包含客户名字和客户等级);
- 服务人员(一个抽象基类+接线员、经理、主管三个继承类,初步设计为包含接电话服务,后续准备加上接电话者工号,是否需要排序等待这些功能)
!!!设计有待完善(关于接线员、经理、主管人数的设计等),先贴上今日版完成的代码。
代码:
#include<iostream>
#include<string>
using namespace std;
class Caller {
public:
Caller(string name, int rank) {
this->mCallername = name;
this->mRank = rank;
};
int getRank(){
return mRank;
};
string getName() {
return mCallername;
};
~Caller(){};
private:
string mCallername;
int mRank;
};
class Woker {
public:
Woker() {};
virtual void handelcall(Caller* caller) = 0;
virtual ~Woker(){};
};
class Director: public Woker {
public:
Director(string name) {this->mDirectorname = name;};
virtual void handelcall(Caller* caller){
if(caller->getRank() == 2) {
cout << "Director" << this->mDirectorname << " is handling " << caller->getName() << "'s call." << endl;
}
else {
cout << "Sorry we can't answer " << caller->getName() << "'s question." << endl;
}
};
virtual ~Director(){};
private:
string mDirectorname;
};
class Manager: public Woker {
public:
Manager(string name) {this->mManagername = name;};
virtual void handelcall(Caller* caller){
if(caller->getRank() == 1) {
cout << "Manager " << this->mManagername << " is handling " << caller->getName() << "'s call." << endl;
}
else {
Woker* woker = new Director("主管1");
woker ->handelcall(caller);
delete woker ;
}
};
virtual ~Manager(){};
private:
string mManagername;
};
class Respondent: public Woker {
public:
Respondent(string name) {this->mRespondentname = name;};
virtual void handelcall(Caller* caller){
if(caller->getRank() == 0) {
cout << "Respondent " << this->mRespondentname << " is handling " << caller->getName() << "'s call" << endl;
}
else {
Woker* woker = new Manager("经理1");
woker->handelcall(caller);
delete woker;
}
};
virtual ~Respondent() {};
private:
string mRespondentname;
};
int main() {
Woker* woker = new Respondent("接线员1");
enum rank{
junior,
middle,
senior,
other
};
Caller* caller1 = new Caller("张三", middle);
Caller* caller2 = new Caller("李四", junior);
Caller* caller3 = new Caller("王五", senior);
Caller* caller4 = new Caller("赵六", other);
woker->handelcall(caller1);
woker->handelcall(caller2);
woker->handelcall(caller3);
woker->handelcall(caller4);
delete woker;
delete caller1;
delete caller2;
delete caller3;
delete caller4;
return 0;
}
结果展示: