我正在开发一个将从命令行调用的程序。根据调用程序时定义的不同标志,该软件将是一种具有不同功能的“套件”。其中一些功能与其他功能大不相同,唯一的相似之处在于它所操作的文件类型。
我想知道实现这种功能的最佳设计模式是什么?我已经阅读了外观设计模式,该模式将每个模块分成不同的子系统。在不同的门面下构建每个功能将保持模块化,并允许我构建一个类来处理要调用的门面。
这是最好的方法,还是你会推荐一些不同的东西?
谢谢,山姆
Jai*_*aro 10
因为这是一个命令行应用程序,我认为命令模式可能对您有用。就个人而言,我认为这是构建控制台应用程序的好方法。
这是支持多个命令的可能实现(在 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);
}
}
Run Code Online (Sandbox Code Playgroud)