为了账号安全,请及时绑定邮箱和手机立即绑定

避免简单的 if/else 条件

避免简单的 if/else 条件

慕标5832272 2022-01-19 09:22:54
在我的程序中,我需要检查变量是否等于 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 条件,但以我的拙见,它只会以不同的方式显示相同的基本功能。我的问题是:有没有办法以优雅和可扩展的方式实现该功能?仅供参考,我已经把这篇文章加红了,但我没有找到适合我的问题的答案。
查看完整描述

3 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

如果您的PhaseOne//类都实现了相同的接口(比方说PhaseTwo),并且在接口上定义了方法,您可以执行以下操作:PhaseThreePhaseperformPhase


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


查看完整回答
反对 回复 2022-01-19
?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

另一种选择是为每个阶段创建一个类和一个 IPhase 接口供他们实现。List<IPhase>使用所有不同的 Phase 实例创建一个。运行一个循环,如果 id 匹配,则执行覆盖的方法。


public interface IPhase {

    public void performPhase();

    public String getId();

}


for (IPhase phase : phasesList){

    if (phase.equals(phase.getId())){

        phase.performPhase();

        // either break or continue the loop

    }

}


查看完整回答
反对 回复 2022-01-19
?
四季花海

TA贡献1811条经验 获得超5个赞

我认为,您所链接问题的公认答案非常适合您。在地图中存储对函数的引用:


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…类不需要公共的超类或接口。


查看完整回答
反对 回复 2022-01-19
  • 3 回答
  • 0 关注
  • 157 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号