各位,我在对代码重构时,有些函数用switch ,太多的case,现把每个case都拿出来做了一个子函数,但是有人说可以用表驱动法进一步优化,也就是不用switch,本人不太明白,请各位不吝赐教。最好给个例子

解决方案 »

  1.   

    写一个 函数指针 的 数组 ,根据原来switch对象,算为数组下标,直接调用。
      

  2.   

    switch编译后就是函数指针表啊你的瓶颈可能不在这里吧 - -
      

  3.   

    如果你的case值都是整数,就按1楼说的,用此整数做数组下标,数组内容 是函数指针.
    否则用hash表.
      

  4.   

    自己解决了,献上源码!
    // MapTest002.cpp : Defines the entry point for the console application.
    //#include "stdafx.h"
    #include "MapTest002.h"
    #include <map>#ifdef _DEBUG
    #define new DEBUG_NEW
    #undef THIS_FILE
    static char THIS_FILE[] = __FILE__;
    #endif/////////////////////////////////////////////////////////////////////////////
    // The one and only application objectCWinApp theApp;using namespace std;
    void t1(CString str)
    {
    printf("1"+str);
    }
    void t2(CString str)
    {
    printf("2"+str);
    }
    void t5(CString str)
    {
    printf("5"+str);
    }
    void t7(CString str)
    {
    printf("7"+str);
    }
    typedef void (* funcT)(CString str);
    map<int,funcT> mFun;void switcTest(int i)
    {
    /*
    switch (i)
    {
    case 1:
    t1("1\n");
    break;
    case 2:
    t2("2\n");
    break;
    case 5:
    t5("5\n");
    break;
    case 7:
    t7("7\n");
    break;
    }
    */
    mFun[i]("ff\n");
    }
    int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
    {
    int nRetCode = 0; // initialize MFC and print and error on failure
    if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    {
    // TODO: change error code to suit your needs
    cerr << _T("Fatal Error: MFC initialization failed") << endl;
    nRetCode = 1;
    }
    else
    {
    // TODO: code your application's behavior here.
    //CString strHello;
    //strHello.LoadString(IDS_HELLO);
    //cout << (LPCTSTR)strHello << endl;
    mFun.insert(pair<int,funcT>(1,&t1));
    mFun.insert(pair<int,funcT>(2,&t2));
    mFun.insert(pair<int,funcT>(5,&t5));
    mFun.insert(pair<int,funcT>(7,&t7));
    switcTest(5);
    } return nRetCode;
    }
      

  5.   

    看看:《重构-改善既有代码的艺术》
    里面有你需要的这个做法的改进方法。
    另外,你这样吧一个switch拆开,也未必就很利于阅读和维护。如果真的就这么简单的结构,那你根本这个方法都多余了。直接用策略模式传递函数指针回调就可以了。