java 用枚举替换多if-else
1、定义抽象类
package com.polaris.design; /** * @author :shi * @date :Created in 2020/8/18 20:15 * @description: * @modified By: */ public abstract class GeneralChannelRule { public abstract void process(); }
2、实现抽象类方法
package com.polaris.design; /** * @author :shi * @date :Created in 2020/8/18 20:18 * @description: * @modified By: */ public class JDChannelRule extends GeneralChannelRule { @Override public void process() { System.out.println("我们大京东!"); } }
3、枚举
package com.polaris.design; /** * @author :shi * @date :Created in 2020/8/18 20:18 * @description: * @modified By: */ public enum ChannelRuleEnum { /** * 京东 */ JD("JD", new JDChannelRule()), /** * 头条 */ TOUTIAO("TOUTIAO", new TouTiaoChannelRule()), /** * 腾讯 */ TENCENT("TENCENT", new TencentChannelRule()); public String name; public GeneralChannelRule channel; ChannelRuleEnum(String name, GeneralChannelRule channel) { this.name = name; this.channel = channel; } //匹配 public static ChannelRuleEnum match(String name) { ChannelRuleEnum[] values = ChannelRuleEnum.values(); for (ChannelRuleEnum value : values) { if (value.name.equals(name)) { return value; } } return null; } public String getName() { return name; } public GeneralChannelRule getChannel() { return channel; } }
4、测试
package com.polaris.design; /** * @author :shi * @date :Created in 2020/8/18 20:27 * @description: * @modified By: */ public class Test1 { public static void main(String[] args) { String sign = "JD"; ChannelRuleEnum channelRule = ChannelRuleEnum.match(sign); GeneralChannelRule rule = channelRule.channel; rule.process(); } }
转自:https://mp.weixin.qq.com/s/faQ3yWYM0swfDoEmtwa3nQ
不要小瞧女程序员