• 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

  • 相关阅读:
    [纯奇技淫巧] 特征根
    杂题20200528
    杂题20200509
    杂题20200419
    杂题20200415
    杂题20200407
    杂题20200314
    Educational Codeforces Round 83 简要题解
    一种简单的dp trick
    杂题20200304
  • 原文地址:https://www.cnblogs.com/shix0909/p/13527299.html
Copyright © 2020-2023  润新知