问题
I have a TcpListener
Listening on a NetworkStream
to perform a command examples. "Copy, Move, Delete, ...."
switch(command)
{
case "copy":
// do copy
break;
case "delete":
// do delete
break;
case "move":
// do move
break;
.......................................
}
i have implemented it using switch - case
and if
statement but when it comes to maintenance or adding a new command, specially when the commands list goes beyond 100 commands it becomes very hard and tedious, so is there a way to do this efficiently, i have tried searching on Google but i can't seem to get the jargon of it correctly
Any help :) Yaser
回答1:
You're looking for Command Pattern. You'll have to create an interface ICommand
and implementation of that interface one per command.
For example: CopyCommand
, DeleteCommand
, MoveCommand
etc.
Then you need a factory method which creates instance of respective ICommand
based on the string provided.
Finally you'll call ICommand.Execute
. That makes it readable, maintainable, clean and so on..
Your code will become
ICommand command = commandFactory.Create(commandString);
command.Execute();
Where commandFactory
is an instance of "Factory" which will create instance of appropriate ICommand
.
Your Factory class could be implemented using a huge switch case or Dictionary<string, Func<ICommand>>
if you prefer.
回答2:
As @Zohar Peled
has already mentioned Dictionary is a really cheap solution for this problem, not so elegant, but really cheap:
//Initialize command lists
Dictionary<string, Action> commands = new Dictionary<string, Action>();
commands.Add("move", DoMyMove);
commands.Add("add", ()=> Console.WriteLine(""));
commands.Add("remove", DoMyRemove);
commands.Add("close", DoMyClose);
delegate
private void DoMyMove()
{
// TODO
}
Usage:
commands[command].Invoke();
It's extendable easly and clear for basic developers...
回答3:
One option is to define a Dictionary<string,action>
on the class level that will hold the name of the command and an action delegate to the actual method that needs to be performed. Then in your main method you don't need to use a switch, simply get the action delegate from the dictionary using the dictionary's TryGetValue Method and if it returns true simply invoke the action delegate.
来源:https://stackoverflow.com/questions/30104924/perform-command-for-list-of-commands-without-using-if-statement-c-sharp