在我的主要方法中,我需要执行系统命令。我正在创建一个外部类来执行命令以保持我的主要方法和应用程序类的清洁。我不确定最好还是最干净的方法是在main方法中为命令进行设置,还是只是将配置读取器传递给该类,然后让它提取所需的东西。

如果仅将外部配置读取器传递给SystemCommand类,是否会使我的应用程序更紧密地耦合或不遵循良好的设计习惯?

示例-从主要方法中进行设置的一种方法:

public static void main (String[] args) {

String[] command = {
    config.getString("program"),
    config.getString("audit.script.name"),
    config.getString("audit.script.config")
    };
String workingDir = config.getString("audit.directory");
SystemCommand runAudit = new SystemCommand(command, workingDir);
runAudit.start();
}


或者,我可以通过将引用传递给config并让类从那里获取需要的内容来简化main方法。看来这种方法在概念上仍然很简单:

public static void main (String[] args) {
SystemCommand runAudit = new SystemCommand(config);
runAudit.start();
}


还有一个配置指定输出和日志记录的位置的问题,但是我还没有想到。

最佳答案

使您的main()方法保持简单。您的main()方法应该不了解程序中其他类的内部细节。这是因为它是一个入口点,通常入口点应该将自身与简约初始化和任何其他内部管理任务相关。解决用例的最佳方法是:

创建一个类SystemCommandFactory,该类将Config实例作为构造函数参数,我在下面假设SystemCommand是可以具有多种实现的接口:

public class SystemCommandFactory
{
     private final Config config;

     public SystemCommandFactory(Config config)
     {
        this.config = config;
     }

    //assume we have a ping system command
    public SystemCommand getPingCommand()
    {
        //build system command
        SystemCommand command1 = buildSystemCommand();
        return command;
    }

    //assume we have a copy system command
    public SystemCommand getCopyCommand()
    {
        //build system command
        SystemCommand command2 = buildSystemCommand();
        return command;
    }
}


现在,您的主要方法将非常简单:

public static void main(String[] args)
{
   SystemCommandFactory factory = new SystemCommandFactory(new Config());

   //execute command 1
   factory.getPingCommand().execute();
   //execute command 2
   factory.getCopyCommand().execute();
}


这样,您可以看到main()方法很简单,并且此设计绝对可以扩展。添加一个新命令说MoveCommand就像这样简单:


为新的创建SystemCommand接口的实现
命令。
在工厂内公开一种新方法以获取新的MoveCommand
main()中,调用此新的factory方法以获取新命令,然后
在其中调用执行。


希望这可以帮助。

07-24 09:38
查看更多