zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    delphi private public protected
    delphi 程序流程控制
    TTrayIcon-Delphi系统托盘组件
    如果没有你-莫文蔚
    ShellExecute 调用bat文件
    delphi ShellExecute使用
    delphi 测试ping
    centos7 安装redis
    my.cnf 基础配置
    Delphi的类和对象(七)- 继承
  • 原文地址:https://www.cnblogs.com/shix0909/p/13527299.html
Copyright © 2011-2022 走看看