是否有任何设计模式可避免嵌套开关盒? [英] Is there any design pattern to avoid a nested switch case?

查看:71
本文介绍了是否有任何设计模式可避免嵌套开关盒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过类似的线程,但是,不确定如何将解决方案正确地应用于我的案例。我的问题是我有一组用例,比如说'A','B','C',当传递的输入(2个用例是输入)是所列用例中的任何2个时,我需要执行某些命令。例如:

I have seen similar kind of threads, But, not sure how to exactly apply the solutions to my case. My problem is that i have a set of usecases lets say 'A','B','C',There are certain commands i need to execute when the input passed(2 usecases are the input) is any 2 of the listed usecases. for example:

switch(input1)
{
case A:
break;
case B:
break;
case C:
break;
}

在每种情况下,我都必须检查输入2,
因此,最终代码可能类似于

inside the each case, i will have to check on input 2, so, the final code could look like

switch(input1)
{
case A:
{
switch(input2):
case B:
break;
case c:
break;
}
case B:
{
switch(input2):
case A:
break;
case c:
break;
}
....

}

我当时正在考虑使用(pair,command)的映射并删除此切换用例,但是有没有其他更好的解决方案或设计问题来解决此问题呢?

I was thinking to use a map of (pair,command) and remove this switch cases, but is there any alternative better solution or design problem to solve this problem?

推荐答案

如果性能不是一个大问题,那么函数指针映射可能是一个解决方案。

If performance is not that a big issue, then a map of function pointers could be one solution.

假设标签 A B C ... 整数值,小于 255

Assuming the label A, B , C ... are small integral values less than 255.


  • 首先设置地图

  • Setup the map first

#define KEY(a,b)  ( (a<<8) | b )

std::map<int, function_pointer_type>  dispatcher =
{
    { KEY(A,B), ab_handler},
    { KEY(A,C), ac_handler},
    { KEY(B,C), bc_handler},
    //etc
};


  • 使用地图为每组输入调用适当的处理程序:

  • Use the map to invoke appropriate handler for each set of input:

     dispatcher[KEY(input1,input2)] (/* args */);
    


  • 请注意,必须使用以下命令设置调度程序每个可能的输入对。另外,如果 KEY(A,B) KEY(B,A)对是相同的情况,那么您可以编写一个名为 invoke 的函数来处理这种情况,以便为其余代码提供统一的用法。

    Note that you have to setup the dispatcher with each possible pair of inputs. Also, if the pair KEY(A,B) and KEY(B,A) are same case, then you can write a function called invoke to handle this case in order to provide uniform usage for the rest of the code.

     void invoke(int input1, int input2, /* args */)
     {
         if (dispatcher.find(KEY(input1, input2)) != dispatcher.end() )
               dispatcher[KEY(input1,input2)] (/* args */);
         else
               dispatcher[KEY(input2,input1)] (/* args */);
     }
    

    然后将其用作:

     invoke(input1, input2, /* args */);
     invoke(input2, input1, /* args */);  //still okay!
    

    希望有帮助。

    这篇关于是否有任何设计模式可避免嵌套开关盒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆