Chain of Responsibility (C++实现)

// Chain of Responsibility.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;
typedef int Topic;

class Handler
{
public:
  Handler(Handler* h= 0, Topic t=-1):successor(h),topic(t)
  {
  } 

virtual ~Handler()
 {
 }

virtual  void HandleRequest(Topic t)=0;
 
 
protected:
   Handler * successor;
   Topic topic;
};

//////////////////////////////////////////////////////

class ConcreteHandler:public Handler
{
public:
 ConcreteHandler(Handler * h=0,Topic t=-1):Handler(h,t)
 {
 }
 virtual ~ConcreteHandler(){}

 virtual void HandleRequest(Topic t)
 {
  if(t==topic)
  {
   cout<<"Done this Request:"<<t<<endl;
   return;
  }
  else
  {
   if(NULL!=successor)
      {
     cout<<"Throw to successor"<<endl;
     successor->HandleRequest(t);
     
     }
  }
   
 }
 
};

int _tmain(int argc, _TCHAR* argv[])
{
 Handler *p1=new ConcreteHandler(0,3);
 Handler *p2=new ConcreteHandler(p1,2);
 Handler *p3=new ConcreteHandler(p2,3);

 Handler *px=new ConcreteHandler(p3);
 //px请求Topic为2.
 px->HandleRequest(2);

 delete p1;
 delete p2;
 delete p3;
 delete px;
 
 return 0;
}

 

posted on 2011-05-27 18:36  IT@民工  阅读(112)  评论(0编辑  收藏  举报

导航