字典表+委托替代switch解决思路

时间:2023-03-09 17:44:35
字典表+委托替代switch解决思路

参考:http://www.jianshu.com/p/8887b3b3e8ba

代码

namespace 解决Switch
{
class Program
{
delegate string func(); static void Main(string[] args)
{
var dict = new System.Collections.Generic.Dictionary<string, func>(); dict["apple"] = new func(apple);
dict["google"] = new func(google);
dict["ibm"] = new func(ibm); string cmd;
while ("exit" != (cmd = System.Console.ReadLine()))
{
if (dict.ContainsKey(cmd))
System.Console.WriteLine(dict[cmd]());
}
} static string apple() { return "apple()哈哈哈"; }
static string google() { return "google()嘻嘻嘻"; }
static string ibm() { return "ibm()呵呵呵"; }
}
}

------解决方案--------------------
这种思路我觉得很好啊,效率比switch更快。switch相当于依次比较的,而字典表只需要比较一次(查一次hash表)更重要的是容易扩展。 
------解决方案--------------------
貌似只有在枚举上才用switch
switch必须是const,除了枚举,没什么写死了的
并且枚举switch的代码可以自动生成 
------解决方案--------------------
这样是可以的。
但是比switch要慢,比if也慢。但是这种模式比较适合分支扩展和运行时注入分支逻辑。
属于消息的一种。从效率上来说与switch和if没法比,这一点可以自行测试。 
------解决方案--------------------
...感觉就是visitor