我在求职面试中需要创建一个客户端-服务器程序,客户端发送命令,服务器处理命令。
服务器需要能够轻松更改,这意味着以后可能会有更多的命令类型。
所以我使用 Strategy 实现了它,这意味着类处理命令看起来类似于:
public class ServerProcessor
{
Dictionary<string, Action<string>> commandsType;
public ServerProcessor()
{
commandsType = new Dictionary<string, Action<string>>();
}
public void RegisterCommand(string commandName, Action<string> command)
{
commandsType.Add(commandName, command);
}
public void Process(string commandName, string vars)
{
if (commandsType.ContainsKey(commandName))
{
commandsType[commandName].Invoke(vars);
}
}
}
在我这样做之后,面试官说我需要使用命令模式来实现它,但没有说明原因。
命令模式将是这样的:
public interface ICommand
{
void Execute(string vars);
string GetName();
}
public class ServerProcessor2
{
List<ICommand> commandsType;
public ServerProcessor2()
{
commandsType = new List<ICommand>();
}
public void RegisterCommand(ICommand commandName)
{
commandsType.Add(commandName);
}
public void Process(string commandName, string vars)
{
foreach (ICommand item in commandsType)
{
string name = item.GetName();
if (name.Equals(commandName))
{
item.Execute(vars);
}
}
}
}
在这种情况下命令模式更好是有原因的,还是只是面试官的观点?
最佳答案
你的两个例子非常相似。他们都使用 Strategy 模式,而不是 Command。
策略封装了一个过程,该过程具有给定类型的输入和另一种给定类型的输出。通常策略的选择取决于输入。
命令模式将系统上的操作表示为易于构建、传输和保存的对象,因此您可以将它们附加到 UI 元素、将它们排队、记录它们、将它们用作撤消的基础等。
您的示例都采用一个带有命令名称的字符串和另一个带有参数的字符串。命令模式将为每个命令使用不同的类(具有公共(public)父类(super class)),并将参数作为对象的属性包含在内。您的示例都使用 Strategy 来执行每个命令;在第一个示例中,您的策略是操作,而在您的第二个示例中,策略是(有点误导)ICommand。您的示例实际上只是在命名上有所不同,一个将其策略存储在字典中,另一个存储在列表中。
现在实际回答您的问题:问题描述中没有任何内容要求使用任一模式。 Command 是客户端-服务器接口(interface)的一个很好的模式,因为它可以实现我上面提到的事情,而 Strategy 是一个很好的执行命令的模式,所以两者都使用是一个不错的选择。然而,两者都不是必需的,据我们所知,Command 只是面试官的选择(可能是因为他们想知道你是否知道)。
关于c# - 命令模式还是策略模式更适合客户端-服务器调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24477771/