如何在java中设计cli选项组合处理程序?

gkl3eglg  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(299)

我需要基于特定的cli组合选项执行一些函数(我使用apachecommons cli库)。

myprogram -a -b ptionArgument -c
myprogram -a -c
myprogram -d optionArgument1 optionArgument2

为了处理这种情况,我有一个非常长的基于特定组合的“else if”列表,所有这些都在我的主要功能中:

if (line.hasOption('a') && line.hasOption('b') && line.hasOption('c')){
   method1();
   method2();
 }
else if (line.hasOption('a') && line.hasOption('c')){
    method4();
 }
else if (line.hasOption('d')){
    method1();
    method4();
 }
....

有没有更好的设计方法(通过使用一些设计模式(例如)。

3phpmpom

3phpmpom1#

我会想出这个办法 CombinationHandler 接口 handle() 方法并创建Map,其中参数是键 CombinationHandler 的是值。之后,您可以简单地添加不同的 CombinationHandler ,并调用它们

interface CombinationHandler {
    void handle();
    // or declare other method signatures
}

public class CombinationComposer  {

    /* key is a merged combination of arguments*/
    private Map<String, List<CombinationHandler>>  handlingStrategies = new HashMap<>();

    public void execute(String arguments) {
        handlingStrategies.getOrDefault(arguments, new ArrayList<>())
                .forEach(CombinationHandler::handle);
    }

    public CombinationComposer() {
        handlingStrategies.put("abc", Lists.asList(
                () -> System.out.println(1),
                () -> System.out.println(2))
        );
    }
}

public static void main(String[] args) {
    String argsString; //squashing array
    new CombinationComposer().execute(argsString);
}

相关问题