I have a need to create a client-server program during a job interview, in which the client sends commands and the server processes them.
The server needs to be able to be able to change easily, meaning that there could be more command types later on.
So I implemented it using Strategy, meaning that the class processing commands looked similar to:
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);
}
}
}
After I did that the interviewer said I needed to implement it using the Command pattern, but did not say why.
The Command pattern will be something like this:
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);
}
}
}
}
is there a reason why the Command pattern is better in this scenario, or is it just the interviewer's point of view?