zoukankan      html  css  js  c++  java
  • 一点心得

    项目中会遇到这样的逻辑处理:根据不同类型调用不同的方法,通常会用到if else等语句,感觉不太好;

    1,应该面向接口编程

    2,尽量避免使用if语句

    实例:原来代码,接口Iservice的实现类有 ServiceA ,ServiceB,ServiceC

    public static void main(String[] args) {
    
            String type = "C";
            Iservice service = null;
            if (type.equals("A")) {
                service = new ServiceA();
            }
            if (type.equals("B")) {
                service = new ServiceA();
            }
            if (type.equals("C")) {
                service = new ServiceA();
            }
    
            service.printMsg();
        }

    上述代码,if语句会随着type取值的增加而增加,需要改动主业务代码

     
    整改
    import java.util.HashMap;
    import java.util.Map;
    
    public class Test {
    
        private static Map<String, Iservice> m = new HashMap<String, Iservice>();
    
        /**
         * @param args
         */
        public static void main(String[] args) {
    
            cache();    
            String type = "B";
            Iservice service = m.get(type);
            service.printMsg();
    
        }
    
        private static void cache() {
            // 緩存
            if (m.isEmpty()) {
                m.put("A", new ServiceA());
                m.put("B", new ServiceB());
                m.put("B", new ServiceB());
            }
        }
    
    }

    如上面代码:以后type类型有新增,只需修改 cache() 方法,增加对应实现即可,不用修改主业务代码



  • 相关阅读:
    MyBatis Plus 导入IdType失败
    SpringBoot+Vue项目上手
    高并发
    多线程
    Java 接口
    Java后端总结
    Aliyun Linux2安装Docker
    Zookeeper集群部署及报错分析
    CentOs7配置java环境
    kafka笔记——kafka启动
  • 原文地址:https://www.cnblogs.com/qqzy168/p/3789413.html
Copyright © 2011-2022 走看看