如何简单的干掉if else

直接上代码,熟以致用:

//原始代码很多if else
public int selectByPrimaryKey(int i)
{
if(i==1){
return 1;
}else if(i==3){
return 3;
}else if(i==4){
return 4;
}
}
首先定义接口:

public interface GetKey
{
int getKey();
}
然后是接口的实现:

Spring种提供的InitializingBean接口,这个接口为Bean提供了属性初始化后的处理方法,它只包括afterPropertiesSet方法,凡是继承该接口的类,在bean的属性初始化后都会执行该方法。

public class Less implements GetKey,InitializingBean
{
@Override
public int getKey() {
return 1;
}

@Override
public void afterPropertiesSet() throws Exception {
    GetKeyFactory.register(1,this);
}

}
public class Middle implements GetKey,InitializingBean
{
@Override
public int getKey() {
return 3;
}

@Override
public void afterPropertiesSet() throws Exception {
    GetKeyFactory.register(3,this);
}

}
public class Big implements GetKey,InitializingBean
{
@Override
public int getKey() {
return 4;
}

@Override
public void afterPropertiesSet() throws Exception {
    GetKeyFactory.register(4,this);
}

}
然后是工厂类:

这个UserPayServiceStrategyFactory中定义了一个Map,用来保存所有的策略类的实例,并提供一个getByUserType方法,可以根据类型直接获取对应的类的实例。只需要每一个策略服务的实现类都实现InitializingBean接口,并实现其afterPropertiesSet方法,在这个方法中调用UserPayServiceStrategyFactory.register即可。

public class GetKeyFactory
{
private static Map<Integer,GetKey> map = new ConcurrentHashMap<Integer,GetKey>();

public static GetKey get(Integer type){
    return map.get(type);
}

public static void register(Integer type,GetKey getKey){
    map.put(type,getKey);
}

}
最后修改过后的版本:

public int selectByPrimaryKey(int i)
{
/* if(i==1){
return 1;
}else if(i==3){
return 3;
}else if(i==){
return 4;
}
*/
GetKey key = GetKeyFactory.get(i);
return key.getKey();
}
至此:我们通过策略模式、工厂模式以及Spring的InitializingBean,提升了代码的可读性以及可维护性,彻底消灭了一坨if-else。

文中的这种做法,使用的并不是严格意义上面的策略模式和工厂模式。

首先,策略模式中重要的Context角色在这里面是没有的,没有Context,也就没有用到组合的方式,而是使用工厂代替了。

另外,这里面的UserPayServiceStrategyFactory其实只是维护了一个Map,并提供了register和get方法而已,而工厂模式其实是帮忙创建对象的,这里并没有用到。

对于设计模式的学习,重要的是学习其思想,而不是代码实现!


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 591235401@qq.com

文章标题:如何简单的干掉if else

本文作者:阿杜同学

发布时间:2019-09-22, 11:47:21

最后更新:2019-09-22, 11:47:21

原始链接:http://yoursite.com/2019/09/22/%E5%A6%82%E4%BD%95%E7%AE%80%E5%8D%95%E7%9A%84%E5%B9%B2%E6%8E%89if-else/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录