2008年4月4日 星期五

Chain of Responsibility

Chain of Responsibility
目的在將一個訊息傳遞下去
讓每個物件都判斷是否有該處理的事情
就像老闆交代一件事情下來,所有員工都問問看,有沒有人會
java awt就是使用這個pattern
有點像linked-list


#define ART 0
#define ENGINEERING 1
#define SCIENCE 2
#define LABOR 3
#define POLITICS 4

class Request {
public:
int request_type;
Request(){}
Request(int type)
{
request_type = type;
}
};

class Handler {
public:
int handler_type;
Handler* next_handler;

Handler()
{
this->next_handler = NULL;
}

void try_handle(Request* request) {
cout << "review request...\n";
if( request->request_type == this->handler_type ) {
this->handle(request);
}
if( this->next_handler != NULL ) {
this->next_handler->try_handle(request);
}
}

void set_next_handler(Handler* next_handler)
{
this->next_handler = next_handler;
}

virtual void handle(Request* request) {

}

};

class DirtyRequest : public Request {
public:
DirtyRequest() : Request(POLITICS) // 這邊算是trick, invoke superclass的constructor必須在code block外面
{}
};

class Engineer : public Handler {
public:
Engineer()
{
this->handler_type = ENGINEERING;
}

virtual void handle(Request* request) {
cout << "Engineer Soloved\n";
}

};

class Artist : public Handler {
public:
Artist()
{
this->handler_type = ART;
}

virtual void handle(Request* request) {
cout << "Artist Soloved\n";
}
};

class Politican : public Handler {
public:
Politican()
{
this->handler_type = POLITICS;
}

virtual void handle(Request* request) {
cout << "Politican Soloved\n";
}
};

int main()
{
Engineer *eng = new Engineer();
Artist *art = new Artist();
art->set_next_handler(eng);
Politican *pol = new Politican();
pol->set_next_handler(art);
pol->try_handle( new DirtyRequest() );

return 0;
}

沒有留言: