粗糙的实现了一个责任链设计模式的例子
#include <iostream>
#include <string>
using namespace std;
class Parent {
public:
Parent();
virtual ~Parent();
private:
Parent(Parent const&);
Parent& operator = (Parent const&);
public:
void SetNextHander(Parent* hander);
virtual int Handle(string request) = 0;
protected:
Parent* handler;
};
class FirstStep : public Parent {
public:
FirstStep(){}
~FirstStep(){}
private:
FirstStep(FirstStep const&);
FirstStep& operator = (FirstStep const&);
public:
int Handle(string request);
};
class SecondStep : public Parent {
public:
SecondStep(){}
~SecondStep(){}
private:
SecondStep(SecondStep const&);
SecondStep& operator = (SecondStep const&);
public:
int Handle(string request);
};
class ThirdStep : public Parent {
public:
ThirdStep(){}
~ThirdStep(){}
private:
ThirdStep(ThirdStep const&);
ThirdStep& operator = (ThirdStep const&);
public:
int Handle(string request);
};
#include "responsibility.h"
Parent::Parent() {
handler = NULL;
}
void Parent::SetNextHander(Parent* handler) {
this->handler = handler;
}
Parent::~Parent() {
if(NULL != handler) {
delete handler;
handler = NULL;
}
}
int FirstStep::Handle(string request) {
if(request == "first") {
cout<< "first process"<< endl;
} else {
if(NULL != handler)
handler->Handle(request);
else
cout<< "FirstStep final"<< endl;
}
return 0;
}
int SecondStep::Handle(string request) {
if(request == "second") {
cout<< "second process"<< endl;
return 1;
} else {
if(NULL != handler)
handler->Handle(request);
else
cout<< "SecondStep final" << endl;
}
return 0;
}
int ThirdStep::Handle(string request) {
if(request == "third") {
cout<< "third process"<< endl;
return 1;
} else {
if(NULL != handler)
handler->Handle(request);
else
cout<< "ThirdStep final" << endl;
}
return 0;
}
责任链设计模式的缺陷就是每个节点都会走一遍,影响性能,但便于扩展