避免过长的IF和Switch分支的方法

避免过长的IF和Switch分支的方法

C#避免过长的IF和Switch分支的方法

1.最蠢形态

//很丑有没有!
//这个分支要是一两个还是可以接受的
class Program
{
static void Main(string[] args)
{
Command("播放");
Console.ReadKey();
} public static void Command(String _command)
{
switch(_command)
{
case "播放":
Console.WriteLine("开始"+_command+"了!!");
break;
case "快进":
Console.WriteLine("开始" + _command + "了!!");
break;
case "暂停":
Console.WriteLine("开始" + _command + "了!!");
break;
case "结束":
Console.WriteLine("开始" + _command + "了!!");
break;
}
}
}

2.表驱动形态

//这个表驱动 还可以利用反射去做
//这个比上面的强多了有没有?
class Program
{ public static Dictionary<string, Action> dic; static void Main(string[] args)
{
dic = new Dictionary<string, Action> {
{"播放", () => { Console.WriteLine("开始播放了!!"); }},
{"快进", () => { Console.WriteLine("开始快进了!!"); }},
{"暂停", () => { Console.WriteLine("开始暂停了!!");}}
};
//可以动态的添加命令和方法
dic.Add("结束", () => { Console.WriteLine("开始结束了!!"); });
Command(dic, "播放");
Command(dic, "快进");
Command(dic, "结束");
Command(dic, "快进两倍"); Console.ReadKey(); } static void Command(Dictionary<string, Action> _dic,String _command)
{
if (_dic.ContainsKey(_command))
{
_dic[_command]();
}
else
{
Console.WriteLine("没有命令啊!!");
}
}
}

3.多态形态

//利用多态来处理
//好处就是再添加命令时候不用修改,直接添加命令类就可以了
class Program
{
static void Main(string[] args)
{
Commander _commander = new PlayCommander();
_commander.Execute(); _commander = new FinishCommander();
_commander.Execute(); _commander = new SpeedCommander();
_commander.Execute(); Console.ReadKey();
}
} abstract class Commander
{
public abstract void Execute();
} class PlayCommander : Commander
{
public override void Execute()
{
Console.WriteLine("开始播放了了!!");
}
} class SpeedCommander : Commander
{
public override void Execute()
{
Console.WriteLine("开始快进了了!!");
}
} class PauseCommander : Commander
{
public override void Execute()
{
Console.WriteLine("开始暂停了了!!");
}
} class FinishCommander : Commander
{
public override void Execute()
{
Console.WriteLine("开始结束了了!!");
}
}
04-30 10:33