避免简单的 if/else 条件

在我的程序中,我需要检查变量是否等于 1、2 或 3,并根据结果执行不同的方法:


if (phase.equals("1")) {

    PhaseOne.performPhase(inputParser.getSource(), inputParser.getTarget());

} else if (phase.equals("2")) {

    PhaseTwo.performPhase(inputParser.getSource(), inputParser.getTarget());

} else {

    PhaseThree.performPhase(inputParser.getSource(), inputParser.getTarget());

}

这段代码是如此简单和基本,但我真的不喜欢它。当然,我可以使用 switch 条件,但以我的拙见,它只会以不同的方式显示相同的基本功能。


我的问题是:有没有办法以优雅和可扩展的方式实现该功能?


仅供参考,我已经把这篇文章加红了,但我没有找到适合我的问题的答案。


慕标5832272
浏览 158回答 3
3回答

慕容708150

如果您的PhaseOne//类都实现了相同的接口(比方说PhaseTwo),并且在接口上定义了方法,您可以执行以下操作:PhaseThreePhaseperformPhasefinal Phase targetPhase;switch(phase) {    case "1": targetPhase = myInstanceOfPhaseOne; break;    case "2": targetPhase = myInstanceOfPhaseTwo; break;    case "3": targetPhase = myInstanceOfPhaseThree; break;    default: throw new IllegalStateException("Unrecognised phase "+phase);}targetPhase.performPhase(inputParser.getSource(), inputParser.getTarget()));

吃鸡游戏

另一种选择是为每个阶段创建一个类和一个 IPhase 接口供他们实现。List<IPhase>使用所有不同的 Phase 实例创建一个。运行一个循环,如果 id 匹配,则执行覆盖的方法。public interface IPhase {&nbsp; &nbsp; public void performPhase();&nbsp; &nbsp; public String getId();}for (IPhase phase : phasesList){&nbsp; &nbsp; if (phase.equals(phase.getId())){&nbsp; &nbsp; &nbsp; &nbsp; phase.performPhase();&nbsp; &nbsp; &nbsp; &nbsp; // either break or continue the loop&nbsp; &nbsp; }}

四季花海

我认为,您所链接问题的公认答案非常适合您。在地图中存储对函数的引用:Map<String,BiConsumer<T,U>> map = new HashMap<>();map.put("1",PhaseOne::performPhase);map.put("2",PhaseTwo::performPhase);map.put("3",PhaseThree::performPhase);map.get(phase).accept(inputParser.getSource(), inputParser.getTarget());将and替换为TandU的类型。inputParser.getSource()inputParser.getTarget()使用这种方法,Phase…类不需要公共的超类或接口。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java