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

posted @   sixinshuier  阅读(876)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示