职责链模式(Chain of Responsibility):
避免发送者和接受者之间的耦合关系,将对象练成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
优点:发送者不用考虑众多接受者之间的数据流,简化了对象的相互链接(仅保持指向后继)。
代码如下:
#include <iostream> #include <vector> using namespace std; /* 职责链模式实现 逐级判断职责 */ class Manager{ private: string name; vector <string> ver; Manager *p; public: Manager(string name) { this->name = name; this->p=NULL; } void SetLeader(Manager *p) { this->p=p; } void Add(string Res) { ver.push_back(Res); } int Respons(string res) { typename vector <string>::iterator it; for(it=ver.begin();it!=ver.end()&&res!=(*it);it++); if(it!=ver.end()){ cout<<name<<"同意请求"<<endl; return 1; }else{ if(this->p){ return this->p->Respons(res); }else{ return 0; } } } }; int main(void) { string want; Manager *Teacher1=new Manager("校长"); Manager *Teacher2=new Manager("院长"); Manager *Teacher3=new Manager("导员"); Manager *Student1=new Manager("班长"); Teacher2->SetLeader(Teacher1); Teacher3->SetLeader(Teacher2); Student1->SetLeader(Teacher3); Teacher2->Add("退学"); Teacher3->Add("请假"); cout<<"输入请求"<<endl; cin>>want; if(!Student1->Respons(want)){ cout<<"请求被驳回"<<endl; } return 0; }