有合适的处理对象就处理,没有就给下一个
这里简化了,有下一个就给下一个
handle.h
#ifndef _HANDLE_H
#define _HANDLE_H
#include <iostream>
using namespace std;
class Handle
{
public:
virtual ~Handle() {
}
Handle() {
}
Handle(Handle* succ) : _succ(succ) {
}
virtual void HandleRequest()=0;
public:
Handle* _succ;
};
class ConcreteHandleA : public Handle
{
public:
ConcreteHandleA() {
}
~ConcreteHandleA() {
}
ConcreteHandleA(Handle* succ) : Handle(succ) {
}
void HandleRequest() {
if (_succ != NULL) {
_succ->HandleRequest();
} else {
cout << "ConcreteHandleA:HandleRequest" << endl;
}
}
};
class ConcreteHandleB : public Handle
{
public:
ConcreteHandleB() {
}
~ConcreteHandleB() {
}
ConcreteHandleB(Handle* succ) : Handle(succ) {
}
void HandleRequest() {
if (_succ != NULL) {
_succ->HandleRequest();
} else {
cout << "ConcreteHandleA:HandleRequest" << endl;
}
}
};
#endif // _HANDLE_H
handle.cpp
#include "handle.h"
int main()
{
Handle* handleA = new ConcreteHandleA;
Handle* handleB = new ConcreteHandleB(handleA);
handleB->HandleRequest();
return 0;
}
编译:make handle
网友评论