场景说明

最近新做一个项目,需要对不同店铺的商品做不同处理。例如storeA需要进行handleA操作,storeB需要进行handleB操作,如此类推

大家很容易会想到下面的实现方法

public void handle(String storeName) {
//店铺A做操作handleA处理
if(storeName.equals("storeA")) {
handleA();
} else if (storeName.equals("storeB")) {
handleB(); //店铺B做操作handleB处理
} else {
//其他处理
}
}

确实上面的代码实现简单易懂,但是如果店铺越来越多,操作也越来越多的情况下,每新增一个店铺都需要在这里添加一次if else,大大的降低了代码的可维护性。

解决办法

这个时候我们会希望可以各个店铺的处理逻辑之间没有关联,互不影响。

抽象接口

我们所有的店铺都会进行对应的操作,所以首先我们将方法抽象出来

public interface Store {
void handle();
}

根据不同店铺做不同处理

@Service("storeA")
public class StoreA implements Store {
@Override
void handle() {
//handleA操作
}
}
@Service("storeB")
public class StoreB implements Store {
@Override
void handle() {
//handleB操作
}
}

添加工厂类

这样还是有问题,因为还是要在业务代码中写if-else来判断到底是哪家store来进行操作,这个时候可以写一个工厂类。


public class StoreFactory { @Autowired
@Qualifier("storeA")
private StoreA storeAA; @Autowired
@Qualifier("storeB")
private StoreB storeBB; //其他实现对象 public Store getStore(String storeName) { if (storeName.equals("storeA")) {
return storeAA;
} else if (storeName.equals("storeB")) {
return storeBB;
}//其他的条件下,返回其他的对象
} }

添加工厂类后,我们在要获取店铺store时只需要调用getStore(String storeName)并传入店铺对象名即可,具体返回哪个对象,是storeA还是storeB,就交给工厂类来处理。

还是免不了写if else,改造StoreFactory

在提供了工厂类之后,还是免不了写很多的条件判断,只不过是把所有的条件判断写在了一起。这时随着产品数量的增多,if else 也会不停地增多,维护起来依然费劲。
这里spring容器就可以派上用场了。spring中有一个BeanFactory对象,也是一个工厂,我们可以用它来改造StoreFactory。

public class StoreFactory {
@Autowired
private BeanFactory beanFactory; public Store getStore(String storeName) {
Object bean = beanFactory.getBean(storeName);
if (bean instanceof Store) {
return (Store) bean;
}
throw new UnsupportedOperationException("不支持的店铺:" + storeName);
}
}

也利用Map自动装配进行代码精简

@Service
public class StoreFactory { @Autowired
Map<String, Store> stores = new ConcurrentHashMap<>(); //会在初始化的时候将所有的Store自动加载到Map中 public Store getStore(String store) {
Store store = stores.get(store);
if (store == null) {
throw new RuntimeException("no store defined");
}
return store;
}
}

@Autowired的源码中有这样一段注释,大意就是@Autowired用于Collection或者Map类型时,容器会自动装配所有已声明的value类型的beans。

/* <p>In case of a {@link java.util.Collection} or {@link java.util.Map} dependency type,
* the container autowires all beans matching the declared value type. For such purposes,
* the map keys must be declared as type String which will be resolved to the corresponding
* bean names. Such a container-provided collection will be ordered, taking into account
* {@link org.springframework.core.Ordered}/{@link org.springframework.core.annotation.Order}
* values of the target components, otherwise following their registration order in the
* container. Alternatively, a single matching target bean may also be a generally typed
* {@code Collection} or {@code Map} itself, getting injected as such.
*/

spring容器干掉if-else的更多相关文章

  1. 一次项目代码重构-使用spring容器干掉条件判断

    一次项目代码重构-使用spring容器干掉条件判断 这是在一次公司项目中进行重构时,一些复杂业务时想到的一个去掉一些if else的办法.能够使代码逻辑更加清晰,减少一些业务上的耦合. 业务说明 我所 ...

  2. 使用spring容器干掉if-else

    spring容器干掉if-else 场景说明 最近新做一个项目,需要对不同店铺的商品做不同处理.例如storeA需要进行handleA操作,storeB需要进行handleB操作,如此类推 大家很容易 ...

  3. 一则spring容器启动死锁问题(DefaultListableBeanFactory/DefaultSingletonBeanRegistry)

    线上发现一个问题,应用在启动时会卡死,log上并没有什么异常输出,初判应该是死锁问题. 抓现场的thread dump文件, 确实是有两个线程有deadlock问题. 线程一 "HSFBiz ...

  4. Spring容器深入(li)

    spring中最常用的控制反转和面向切面编程. 一.IOC IoC(Inversion of Control,控制倒转).对于spring框架来说,就是由spring来负责控制对象的生命周期和对象间的 ...

  5. 通过单元测试理解spring容器以及dubbo+zookeeper单元测试异常处理

    一.先说一个结论:单元测试与主项目的spring容器是隔离的,也就是说,单元测试无法访问主项目spring容器,需要自己加载spring容器. 接下来是代码实例,WEB主项目出于运行状态,单元测试中可 ...

  6. 同时使用Junit4的@Parameterized参数化测试和Spring容器

    转载:http://www.jianshu.com/p/d191fe54915f 整合Spring容器 @SpringApplicationConfiguration(classes = Applic ...

  7. Spring 容器

    Spring提供了两个核心接口:BeanFactory和ApplicationContext,其中applicationContext是BeanFactory的子接口. 他们都可代表Spring容器, ...

  8. Spring-Context之四:Spring容器及bean的定义

    Spring框架的核心功能之一就是控制反转(Inversion of Control, IoC),也叫做依赖注入(dependency injection, DI).关于依赖注入的具体内容可以参见Ma ...

  9. spring容器对bean生命周期的管理三中方式

    spring容器对bean的生命周期管理主要在两个时间点:bean的初始化完成(包括属性值被完全注入),bean的销毁(程序结束,或者引用结束)方式一:使用springXML配置中的init-meth ...

随机推荐

  1. prometheus学习系列八: Prometheus Grafana展示平台

    在prometheus中,我们可以使用web页面进行数据的查询和展示, 不过展示效果不太理想,这里使用一款专业的展示平台进行展示. grafana安装 # 下载wget https://dl.graf ...

  2. 关于IE环境下按回车键会自动触发button 按钮的点击事件的解决方案

    今天项目中遇到IE不兼容的问题,于是就根据问题进行修改,修改过程中发现,在输入框内用扫码枪扫描东西后会自动执行页面下面的button按钮,但是其它浏览不会出现这样的问题. 解决方案: 1.用a标签 2 ...

  3. Kali在NET模式下不能联网的解决方法

    1.第一种情况 首先ifconfig,可以看到没有正在工作的网卡,只有localhost 然后ifconfig -a,可以看到eth0这块网卡并没有离家出走,只是罢工了而已 接下来是关键步骤 leaf ...

  4. 利用 Docker 搭建 IPFS 私有网络

    利用 Docker 搭建 IPFS 私有网络 本文原始地址:https://sitoi.cn/posts/40630.html 下载项目 项目地址:https://github.com/Sitoi/p ...

  5. flask 源码浅析(flask 如何处理请求(多线程,多进程,IO多路复用))

    2018-04-04 13:09:47 lucky404 阅读数 5724更多 分类专栏: python   版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接 ...

  6. vue.js集成codeMirror代码编辑器

    1.前端代码 <link href="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.css" rel=" ...

  7. Java 并发,相关术语

    Java 并发,相关术语: 术语 作用 synchronize 可修饰方法.代码块.类:介绍:https://www.cnblogs.com/zyxiaohuihui/p/9096882.html L ...

  8. python + redis +ipset实现IP黑名单的动态添加及解封禁

    1.抽空用python做了一个 动态添加/删除IP黑名单 的程序(或者说实现方案),项目地址: https://gitee.com/lowmanisbusy/ip_blacklists, 2.这里的实 ...

  9. CustomHTTPProtocol

    http://blog.csdn.net/jingcheng345413/article/details/54967739 一.概念 NSURLProtocol也是苹果众多黑魔法中的一种,使用它可以轻 ...

  10. 编程语言的类型修饰符modifiers

    编程语言修饰符,代表语言要素与常规表达不同的语义: 这些语义的不同需要编译器和运行时作出不同的解释: 作用域.访问: 生命周期: 同步异步: 多态: 纯函数: 注解: 懒加载: 编译器合成: