【发布时间】:2014-08-20 02:17:20
【问题描述】:
我需要在求职面试期间创建一个客户端-服务器程序,其中客户端发送命令,服务器处理它们。
服务器需要能够轻松更改,这意味着以后可能会有更多的命令类型。
所以我使用 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);
}
}
}
}
在这种情况下命令模式更好的原因是什么,还是只是面试官的观点?
【问题讨论】:
-
我认为你问的问题太宽泛了。我不确定面试官是否足够清楚地提出了这个问题,是否有足够的要求来证明对战略的指挥是合理的。面试官也是人,而且以提出不好的问题而臭名昭著。很难正确地设置问题以使模式显而易见(不要太明显)。
-
@Fuhrmanator,我已经看到你提到的问题,但我的问题很具体,不像“有什么区别”那么广泛,我只想说这是我希望的问题听到,或了解我的错误。
标签: c# design-patterns strategy-pattern command-pattern