标签:
职责链模式:
对于一个请求,自己处理不了的,交于上级处理,形成了一个职责链,依次交于上级处理
// Responsibility.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <STRING> using namespace std; class Business{ public: void setprice(int price){ m_price = price; } int getprice(){ return m_price; } protected: int m_price; }; class Manager{ public: Manager(string name):m_name(name){} virtual void handle(Business * bus) = 0; void setsuper(Manager * other){ this->super = other; } virtual ~Manager(){} protected: string m_name; Manager * super; }; class TownManager:public Manager{ public: TownManager(string name):Manager(name){} void handle(Business * bus){ if(bus->getprice() < 10000){ cout<<this->m_name<<" handle "<<bus->getprice()<<endl; } else{ if(bus != NULL){ this->super->handle(bus); } } } }; class CityManager:public Manager{ public: CityManager(string name):Manager(name){} void handle(Business * bus){ if(bus->getprice() < 20000){ cout<<this->m_name<<" handle "<<bus->getprice()<<endl; } else{ if(bus != NULL){ this->super->handle(bus); } } } }; class CountryManager:public Manager{ public: CountryManager(string name):Manager(name){} void handle(Business * bus){ if(bus->getprice() < 30000){ cout<<this->m_name<<" handle "<<bus->getprice()<<endl; } else{ if(bus != NULL){ cout<<this->m_name<<" 有点麻烦"<<endl; } } } }; int main(int argc, char* argv[]) { Manager * ptown = new TownManager("镇公司"); Manager * pcity = new CityManager("市公司"); Manager * pcoun = new CountryManager("国家公司"); ptown->setsuper(pcity); pcity->setsuper(pcoun); Business * pbusiness = new Business; int array[3] = {5000,15000,25000}; for(int i = 0;i<3;i++){ pbusiness->setprice(array[i]); ptown->handle(pbusiness); } delete ptown; delete pcity; delete pcoun; delete pbusiness; return 0; }
标签:
原文地址:http://www.cnblogs.com/xiumukediao/p/4653656.html