C++设计模式之职责链模式

代码实现:

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

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;


class Manager
{
protected:
    Manager *m_manager;
    string m_name;
public:
    Manager(Manager* manager,string name):m_manager(manager),m_name(name){}
    virtual void DealWithRequest(string name, int num) {}
};

class CommonManager : public Manager
{
public:
    CommonManager(Manager* manager,string name):Manager(manager,name){}
    void DealWithRequest(string name,int num)
    {
        if(num < 500)
        {
            cout << "经理" <<m_name << "批准" << name << "加薪" << num << "" <<endl;
        }
        else
        {
            cout << "经理" << m_name << "无法处理,交由总监处理" <<endl;
            m_manager->DealWithRequest(name,num);
        }
    }
};

class Majordomo:public Manager
{
public:
    Majordomo(Manager *manager,string name):Manager(manager,name){}
    virtual void DealWithRequest(string name,int num)
    {
        if(num < 1000)
        {
            cout << "总监" <<m_name << "批准" << name << "加薪" << num << "" <<endl;
        }
        else
        {
            cout << "总监" << m_name << "无法处理,交由总经理处理" <<endl;
            m_manager->DealWithRequest(name,num);
        }
    }
};

class GeneralManager : public Manager
{
public:
    GeneralManager(Manager *manager,string name):Manager(manager,name){}
    void DealWithRequest(string name,int num)
    {
        cout << "总经理" <<m_name << "批准" << name << "加薪" << num << "" <<endl;
    }
};
int _tmain(int argc, _TCHAR* argv[])
{
    Manager *general = new GeneralManager(NULL,"a");
    Manager *majordomo = new Majordomo(general,"b");
    Manager *common = new CommonManager(majordomo,"c");
    common->DealWithRequest("d",400);
    common->DealWithRequest("d",700);
    common->DealWithRequest("d",1200);
    system("pause");
    return 0;
}

 

posted @ 2018-07-12 18:11  wxmwanggood  阅读(134)  评论(0编辑  收藏  举报