【发布时间】:2017-04-30 16:23:37
【问题描述】:
我有一堆命令需要从客户端批处理并在服务器上执行。这些命令具有不同的类型,命令的契约和相应的返回类型通过库在客户端和服务器之间共享。
客户端代码如下-
var client = new ClientSDK();
client.Add(new Command1());
client.Add(new Command2());
client.Add(new Command3());
// Execute transmits all the commands to the server
var results = client.Execute();
服务器代码 -
List<CommandResult> Execute(List<CommandBase> commands)
{
List<CommandResult> results = new List<CommandResult>();
foreach(CommandBase command in commands)
{
if(command.GetType == Command1)
{
results.Add(new Command1Executor(command).Execute())
}
else if(command.GetType == Command2)
{
results.Add(new Command1Executor(command).Execute())
}
else if(command.GetType == Command3)
{
results.Add(new Command3Executor(command).Execute())
}
..................
}
}
对于每个命令,都有一个独特的执行函数,不能作为客户端 SDK 的一部分公开。如何进行设计更改,以便摆脱大量的 if/else 块?有大量的命令需要支持。我尝试按照这里的建议应用命令模式 - using the command and factory design patterns for executing queued jobs 但这需要每个命令都实现 ICommand 接口,这是不可能的
有更好的设计方法吗?
【问题讨论】:
-
将所有命令执行器(或创建它们的函数)放入字典中,按命令类型键入。这样你就不需要 if else 链。
标签: c# design-patterns client-server factory-pattern command-pattern