默默地EEer,原文地址:
http://www.cnblogs.com/hebaichuanyeah/p/5625233.html
职责链模式指使多个对象多有机会处理请求,避免请求发送者和接受者的耦合关系。
将这些接受处理的对象连成一条链,并沿着该链处理请求。
一个传说中的应用情景:
假如去政府部门办事,遇到了打字员小丽,在打LOL的小张以及主任老李,互相踢皮球推脱。
#include <iostream>
using namespace std;class Handler
{
protected:string name;Handler * successor;
public:Handler(){}virtual ~Handler(){}void setSuccessor(Handler * successor){this->successor = successor;}string getName(){return name;}virtual void HandleRequest(string str){}
};
//传说中的政府部分踢球皮球人员
class FootballPlayer : public Handler
{
public:FootballPlayer(string name){this->name = name;}virtual void HandleRequest(string str){if(name == str){cout<<this->name<<": 办理事务.."<<endl;}else if(successor != NULL){cout<<this->name<<": 这个不归我管,你去找"<<successor->getName()<<endl;successor->HandleRequest(str);}else{cout<<this->name<<": 这个办不了啦"<<endl;}}
};main()
{Handler * xiaoli = new FootballPlayer("打字员小丽");Handler * xiaozhang = new FootballPlayer("在打lol的小张");Handler * laoli = new FootballPlayer("主任老李");//小丽把皮球踢给小张xiaoli->setSuccessor(xiaozhang);xiaozhang->setSuccessor(laoli);laoli->setSuccessor(NULL);xiaoli->HandleRequest("办个事");
}