【发布时间】:2010-03-22 15:12:48
【问题描述】:
这种模式经常出现。这看起来像是一种非常冗长的方法,可以将原本单独的命名方法移动到单个方法中,然后通过参数进行区分。
是否有充分的理由让这种模式超过只有两个方法 Method1() 和 Method2() ?真正的问题是,这种模式往往只在运行时使用常量调用——即在编译完成之前参数都是已知的。
public enum Commands
{
Method1,
Method2
}
public void ClientCode()
{
//Always invoked with constants! Never user input.
RunCommands(Commands.Method1);
RunCommands(Commands.Method2);
}
public void RunCommands(Commands currentCommand)
{
switch (currentCommand)
{
case Commands.Method1:
// Stuff happens
break;
case Commands.Method2:
// Other stuff happens
break;
default:
throw new ArgumentOutOfRangeException("currentCommand");
}
}
【问题讨论】:
标签: c# java design-patterns switch-statement