避免使用简单的if/else条件
创始人
2024-12-16 15:00:21
0

避免使用简单的if/else条件可以使用多种方法来达到同样的效果,如下所示:

  1. 使用switch语句替代if/else条件:
int num = 2;
String result = "";

switch(num) {
    case 1:
        result = "One";
        break;
    case 2:
        result = "Two";
        break;
    case 3:
        result = "Three";
        break;
    default:
        result = "Other";
}

System.out.println(result);
  1. 使用字典或映射表替代if/else条件:
Map map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");

int num = 2;
String result = map.getOrDefault(num, "Other");

System.out.println(result);
  1. 使用策略模式来避免复杂的if/else条件:
interface Strategy {
    String getResult(int num);
}

class OneStrategy implements Strategy {
    @Override
    public String getResult(int num) {
        return "One";
    }
}

class TwoStrategy implements Strategy {
    @Override
    public String getResult(int num) {
        return "Two";
    }
}

class ThreeStrategy implements Strategy {
    @Override
     public String getResult(int num) {
        return "Three";
    }
}

class Context {
    private Strategy strategy;

    public Context(Strategy strategy) {
        this.strategy = strategy;
    }

    public String executeStrategy(int num) {
        return strategy.getResult(num);
    }
}

public class Main {
    public static void main(String[] args) {
        int num = 2;

        Context context = new Context(new TwoStrategy());
        String result = context.executeStrategy(num);

        System.out.println(result);
    }
}

这些方法可以帮助我们更好地组织代码,使其更易读、易维护,并且避免了简单的if/else条件。

相关内容

热门资讯

三分钟绝活儿!wpk辅助购买(... 三分钟绝活儿!wpk辅助购买(透视)好像是真的有辅助辅助(哔哩哔哩)1、wpk辅助购买辅助器安装包、...
六分钟模板!大菠萝辅助器(透视... 六分钟模板!大菠萝辅助器(透视)其实真的有辅助工具(哔哩哔哩)运大菠萝辅助器辅助工具,进入游戏界面。...
第8分钟办法!wepoker透... 第8分钟办法!wepoker透视脚本(透视)原来真的是有辅助开挂(哔哩哔哩)1、wepoker透视脚...
第二分钟积累!newpoker... 第二分钟积累!newpoker脚本(透视)果然存在有辅助工具(哔哩哔哩)newpoker脚本透视方法...
第4分钟攻略!德州来玩辅助器(... 第4分钟攻略!德州来玩辅助器(透视)本来真的有辅助下载(哔哩哔哩)小薇(辅助器软件下载)致您一封信;...
6分钟绝活儿!aapoker怎... 6分钟绝活儿!aapoker怎么控制牌(透视)好像有辅助开挂(哔哩哔哩)1、aapoker怎么控制牌...
七分钟指南书!aapoker破... 七分钟指南书!aapoker破解侠是真的吗(透视)原来存在有辅助教程(哔哩哔哩)暗藏猫腻,小编详细说...
第3分钟法门!智星德州插件(透... 第3分钟法门!智星德州插件(透视)好像真的有辅助辅助(哔哩哔哩)1、下载好智星德州插件脚本下载之后点...
1分钟机巧!wepoker到底... 1分钟机巧!wepoker到底有没有透视(透视)果然是有辅助开挂(哔哩哔哩)1、下载好wepoker...
7分钟学习!wepoker养号... 7分钟学习!wepoker养号规律(透视)总是有辅助辅助(哔哩哔哩)1)wepoker养号规律免费钻...