zoukankan      html  css  js  c++  java
  • C++的一种业务分发方案(另类的工厂模式)

    在C++中,传统的业务分发。总要写一大串的switch-case,并且每次添加新业务时。都要在原有的switch-case里加一个分支,这就违反了设计模式中的开放封闭原则。

    下面这样的方案,就全然去除了switch-case。每当要加入业务模块时。仅仅要写一个TEST_MODULE(index, name)就能够了。

    思路非常easy,直接上代码:
    #include <iostream>
    #include <string>
    #include <map>
    using namespace std;
    
    //业务模块,第一个參数是模块ID,第二个是模块名称
    //用了C语言的一些技巧。嘿嘿
    #define TEST_MODULE(index, name) 
        void test_##name(int num);     
        TempFunction fun_##name(index, test_##name);  
        void test_##name(int num)
    
    //模块中所使用的回调函数
    typedef void (*MODULE_FUNCTION)(int num); 
    
    //模块管理类(单例)
    class ModuleFactory
    {
    private:
        map<int, MODULE_FUNCTION> m_ModuleMap;
    
        ModuleFactory() { }
        ~ModuleFactory() { }
    
    public:
        static ModuleFactory *GetInstance()
        {
            static ModuleFactory instance;
            return &instance;
        }
    
        //返回总的业务个数
        int BusinessCount() 
        { return m_ModuleMap.size(); }
    
        //载入业务(假设业务号有反复,就输出一条信息,然后退出程序)
        void AddBusiness(int index, MODULE_FUNCTION fun)
        { m_ModuleMap[index] = fun; }
    
    
        //运行业务
        void RunFunction(int index, int num)
        {
            map<int, MODULE_FUNCTION>::iterator iter = m_ModuleMap.find(index);
            if( iter == m_ModuleMap.end() )
                cout << "no this module: " << index << endl;
            else
                iter->second(num);
        }
    };
    
    //暂时类。利用了“全局变量的构造函数必然会会在main函数之前被运行这个特点
    class TempFunction
    {
    public:
        TempFunction(int index, MODULE_FUNCTION fun) 
        { ModuleFactory::GetInstance()->AddBusiness(index, fun); }
    };
    
    
    //三个业务模块
    //每当要加入业务模块时,仅仅要写一个TEST_MODULE(index, name)就能够了
    TEST_MODULE(1, aaa)
    {
        cout << "aaa: " << num << endl;
    }
    
    TEST_MODULE(2, bbb)
    {
        cout << "bbb: " << num << endl;
    }
    
    TEST_MODULE(3, ccc)
    {
        cout << "ccc: " << num << endl;
    }
    
    //測试样例
    int main()
    {
        int index, num;
        while( cin >> index >> num )
        {
            ModuleFactory::GetInstance()->RunFunction(index, num);
        }
        return 0;
    }


查看全文
  • 相关阅读:
    Server Tomcat v8.0 Server at localhost was unable to start within 45 seconds. If the server requires more time, try increasing the timeout in the server editor.
    用户画像——“打标签”
    python replace函数替换无效问题
    python向mysql插入数据一直报TypeError: must be real number,not str
    《亿级用户下的新浪微博平台架构》读后感
    【2-10】标准 2 维表问题
    【2-8】集合划分问题(给定要分成几个集合)
    【2-7】集合划分问题
    【2-6】排列的字典序问题
    【2-5】有重复元素的排列问题
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10795536.html
  • Copyright © 2011-2022 走看看