还在用繁琐的if..else,试试策略模式吧!
前言
应该有不少码友遇到过充斥着if else的代码,面对这样的一团乱麻,简单粗暴地继续增量修改常常只会让复杂度越来越高,可读性越来越差。那么是时候重构了,花几分钟看看这篇文章, 说不定对你有一丢丢帮助。
业务场景
有这么一个小需求,需要对不同类型的用户进行不同规则的操作,场景大概如下所示:
if (普通用户) {
 // 此处省略...
}
if (会员用户) {
  // 此处省略...
}
if (钻石用户) {
  // 此处省略...
}
 
按照上述的条件我们可以得出的结论是:
根据现在的流程来看,如果有一个不匹配的话,其实后续的流程是不用执行的,就是需要具备一个短路的功能。对于目前的现状来说,如果在原有的基础上来改,只要稍微注意一下解决现在的需求不是很大的问题,但是后面可维护性非常差。
策略模式
策略模式属于对象的行为模式。其用意是针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。
策略模式是对算法的包装,是把使用算法的责任和算法本身分割开来,委派给不同的对象管理。策略模式通常把一个系列的算法包装到一系列的策略类里面,作为一个抽象策略类的子类。用一句话来说,就是:“准备一组算法,并将每一个算法封装起来,使得它们可以互换”。
这个模式涉及到三个角色:
-  
环境(Context)角色:持有一个Strategy的引用。
 -  
抽象策略(Strategy)角色:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
 -  
具体策略(ConcreteStrategy)角色:包装了相关的算法或行为。
 
优化方案
使用普通的策略模式进行优化。
1.定义接口:
public interface Type {
    /**
     * 获取类型,返回集合
     */
    Bollean userRule();
}
 
2.定义 UserType(普通)实现 Type 接口:
@Service
public class UserType implements Type {
    @Override
    public Bollean userRule() {
        // 此处省略普通用户的规则操作...
        return true;
    }
}
 
3.定义 VIPUserType(vip用户)实现 Type 接口:
@Service
public class VIPUserType implements Type {
    @Override
    public Bollean userRule() {
        // 此处省略普通用户的规则操作...
        return true;
    }
}
 
4.定义策略工厂类:
public class TypeFactory {
    private static TypeFactory typeFactory = new TypeFactory();
    
    // 定义Map
    private static Map<Integer,Type> map = new HashMap<>();
    
    static{
        map.put(1, new UserType());
        map.put(2, new VIPUserType())
    }
    public static TypeFactory getInstance(){
        return typeFactory;
    }
    public Type getByType(Integer type){
        return map.get(type);
    }
}
 
5.使用
TypeFactory.getInstance().getByType(1).userRule();
 
问题
在上面策略模式中如果在实现类 UserType 中使用
@Autowired
private Dao dao;
 
就会出现 空指针的情况
java.lang.NullPointerException
 
因为 发现策略实现中的Dao接口注入的都是Null。
改造
@Service("userType")
public class UserType implements Type {
    @Autowired
    private Dao dao;
    @Override
    public Bollean userRule() {
        // 此处省略普通用户的规则操作...
        return true;
    }
}
 
@Service("vIPUserType")
public class VIPUserType implements Type {
    @Autowired
    private Dao dao;
    @Override
    public Bollean userRule() {
        // 此处省略普通用户的规则操作...
        return true;
    }
}
 
public class TypeFactory {
    @Resource
    @Qualifier("userType")
    private  UserType userType;
    @Resource
    @Qualifier("vIPUserType")
    private  VIPUserType vIPUserType;
    
    public  Type getByType(Integer type){
        Map<Integer, Type> map = new HashMap<>();
        map.put(1, userType);
        map.put(2, vIPUserType);
        return map.get(type);
    }
}
 
public class Test {
    // 工厂注入
    @Autowired
    private TypeFactory typeFactory;
    @GetMapper("/test")
    public void test(Integer type) {
        typeFactory.getByType(type).getType()
    }
}
 
欢迎关注我的公众号“阿轩学Java”,原创技术文章第一时间推送。
 
                    
                
                
            
        
浙公网安备 33010602011771号