如何简单的干掉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方法而已,而工厂模式其实是帮忙创建对象的,这里并没有用到。

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值