如何简单的干掉if else

编程入门 行业动态 更新时间:2024-10-09 23:23:16

如何<a href=https://www.elefans.com/category/jswz/34/1770983.html style=简单的干掉if else"/>

如何简单的干掉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
{@Overridepublic int getKey() {return 1;}@Overridepublic void afterPropertiesSet() throws Exception {GetKeyFactory.register(1,this);}
}
public class Middle implements GetKey,InitializingBean
{@Overridepublic int getKey() {return 3;}@Overridepublic void afterPropertiesSet() throws Exception {GetKeyFactory.register(3,this);}
}
public class Big implements GetKey,InitializingBean
{@Overridepublic int getKey() {return 4;}@Overridepublic 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方法而已,而工厂模式其实是帮忙创建对象的,这里并没有用到。

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

更多推荐

如何简单的干掉if else

本文发布于:2024-02-13 18:23:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1759404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简单

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!