gpt4 book ai didi

design-patterns - 具有多种功能的命令行软件的设计模式

转载 作者:行者123 更新时间:2023-12-05 00:14:24 24 4
gpt4 key购买 nike

我正在开发一个将从命令行调用的程序。该软件将是一种“工具包”,具有基于调用程序时定义的不同标志的不同功能。其中一些功能与其他功能大不相同,唯一的相似之处在于它所操作的文件类型。

我想知道实现这种功能的最佳设计模式是什么?我已经阅读了有关将每个模块拆分为不同子系统的外观设计模式。在不同的外观下构建每个功能将使其模块化,并允许我构建一个单独的类来处理要调用的外观。

这是最好的方法吗,还是你会推荐一些不同的东西?

谢谢,
山姆

最佳答案

因为这是一个命令行应用程序,我认为 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);
}
}

关于design-patterns - 具有多种功能的命令行软件的设计模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46956699/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com