2

我有方法应该在同一过程结束时获得不同的参数,因为需要以不同的方式执行该过程

我的问题是这是最好的方法,假设这是 API

void action(String a,String b){
    functionA();
    functionB();
    functionC();
}




void action(String a){
    functionA();
    functionC();
}


void action(String a,String B,String C){
    functionA();
    functionC();
    functionD();
}

我问的原因是你可以看到我总是使用functionA 和 functionC?在java中有更优雅的方法吗?

4

2 回答 2

2

您可以在重载函数之间共享代码,重载函数之间共享代码是非常合乎逻辑的。

//this delegates what happens to 'a' to the lower link, passing the responsibility to it along the 'chain'
void action(String a,String b){
    action(a);
    functionB();
}
//this delegates what happens to 'a' to the lower link, passing the responsibility to it along the 'chain'
void action(String a,String B,String C){
    action(a);
    functionD();
}
//this is the lowest link in your chain of responsibility, it handles the one parameter case
void action(String a){
    functionA();
    functionC();
} 
于 2013-02-10T10:26:42.677 回答
0

你的问题不是很清楚,但是看看Command Pattern。您实际上可以从不同的子命令构建命令。

像这样的东西?

public class CommandExample {

    private final Map<String, Command> availableCommands;

    CommandExample() {
        availableCommands = new HashMap<>();
        List<Command> cmds = Arrays.asList(new Command[]{new CommandA(), new CommandB(), new CommandC(), new CommandD()});
        for (Command cmd:cmds)
            availableCommands.put(cmd.getId(), cmd);
    }
    public interface Command {
        public String getId();
        public void action();
    }

    public class CommandA implements Command {
        @Override 
        public String getId() {
            return "A";
        }
        @Override
        public void action() {
            // do my action A
        }
    }
    public class CommandB implements Command {
        @Override 
        public String getId() {
            return "B";
        }
        @Override
        public void action() {
            // do my action B
        }
    }
    public class CommandC implements Command {
        @Override 
        public String getId() {
            return "B";
        }
        @Override
        public void action() {
            // do my action C
        }
    }
    public class CommandD implements Command {
        @Override 
        public String getId() {
            return "C";
        }
        @Override
        public void action() {
            // do my action D
        }
    }


    public void execute(String[] input) {
        for (String in: input) {
            availableCommands.get(in).action();
        }
    }
}
于 2013-02-10T10:31:15.350 回答