有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

JavaOOD将配置传递给外部类的最佳方式

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

如果我只是将外部配置读取器传递给我的SystemCommand类,它会使我的应用程序更紧密地耦合还是不遵循良好的设计实践

Ex-从主方法到设置的方法1:

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();
}

或者,我可以通过传递对配置的引用并让类从中提取所需内容来简化main方法。这种方法在概念上似乎仍然很简单:

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

还有一个问题是在指定输出和日志的位置进行配置,但我还没有考虑清楚


共 (1) 个答案

  1. # 1 楼答案

    保持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()方法是简单干净的,并且这种设计绝对是可扩展的。添加新命令sayMoveCommand非常简单:

    1. 为新应用程序创建SystemCommand接口的实现 指挥部
    2. 在工厂中公开一个新方法以获取这个新的MoveCommand
    3. main()中,调用这个新的工厂方法来获取新的命令和 在其中调用execute

    希望这有帮助