因为这是一个命令行应用程序,我认为
Command pattern
这是一种可能的实现(在c语言中)来支持多个命令:
// The main class, the entry point to the program
internal class Program
{
private static void Main(string[] args)
{
var p = new Processor();
p.Process(args);
}
}
/* The command processor class, its responsibility is to take its input parameters to create the command and execute it. */
public class Processor
{
private CommandFactory _commandFactory;
public Processor()
{
_commandFactory = new CommandFactory();
}
public void Process(string[] args)
{
var arguments = ParseArguments(args);
var command = _commandFactory.CreateCommand(arguments);
command.Execute();
}
private CommandArguments ParseArguments(string[] args)
{
return new CommandArguments
{
CommandName = args[0]
};
}
}
/* Creates a command based on command name */
public class CommandFactory
{
private readonly IEnumerable<ICommand> _availableCommands = new ICommand[]
{
new Command1(), new Command2(), .....
};
public ICommand CreateCommand(CommandArguments commandArguments)
{
var result = _availableCommands.FirstOrDefault(cmd => cmd.CommandName == commandArguments.CommandName);
var command = result ?? new NotFoundCommand { CommandName = commandArguments.CommandName };
command.Arguments = commandArguments;
return command;
}
}
public interface ICommand
{
string CommandName { get; }
void Execute();
}
/* One of the commands that you want to execute, you can create n implementations of ICommand */
public class Command1 : ICommand
{
public CommandArguments Arguments { get; set; }
public string CommandName
{
get { return "c1"; }
}
public void Execute()
{
// do whatever you want to do ...
// you can use the Arguments
}
}
/* Null object pattern for invalid parametters */
public class NotFoundCommand : ICommand
{
public string CommandName { get; set; }
public void Execute()
{
Console.WriteLine("Couldn't find command: " + CommandName);
}
}