前言:
工厂模式可以为我们的代码更加灵活维护。有个需求是多种角色进行查询,判断每种角色然后进行不同的逻辑处理,如果按照普通方法来写,大概处理是这样的 ↓
if("role".equals("1")){
//角色1查询
}else if("role".equals("2")){
//角色2查询
}else if("role".equals("3")){
//角色3查询
}......
这样的写的好处是比较简单,开发一时爽。不好的点是不利于后期的维护,代码耦合重,各个角色的关系不清晰,需要依靠大量的if else来进行判断,代码自然就显得冗余了
方案:
如果按照上面的方法进行开发,每个if下面都会有很杂很乱的代码语句,就算封装方法也是让人看着不舒服的。换个角度想,为什么不能解放各个角色,达到每个角色只专注于做自己的事情,代码实现解耦,尽量一个模块只专注于做一件事情。
1.工厂类,使用工厂类创建对应角色,输入角色code,就能自动返回角色对象。
if(roleNum.equals("1")){
return new AirportStaffImpl();
}else if(roleNum.equals("2")){
return new SupervisorImpl();
}else if(roleNum.equals("3")){
return new RepairmanImpl();
}
throw new ExceptionMsg("不存在的角色!");
2.接口类,用每种角色实现抽象,共同使用一个方法。
public interface MaintainTaskPeople{
Page<MaintainTaskEntity> queryMaintainTask(MaintainTaskEntity entity);
}
3.为每种角色创建一个类,实现独立。
问题:
我这里写的是有问题的,在进行角色逻辑处理的时候调用dao数据库交互方法会报空指针异常,
@Autowired
private MaintainTaskDao maintainTaskDao;
后来检查了解后发现@Autowired注入时是将bean交给Springboot管理而new出来的对象不在Springboot的管理范围内。这时候@Autowired注入就会为null。
if(roleNum.equals("1")){
//不能直接new
return new AirportStaffImpl();
}
throw new ExceptionMsg("不存在的角色!");
所以工厂类生产对象不能直接new出对象。
总结,如果该类要使用@Autowire,该类必须在SpringBean容器中拿实例(bean),而不能直接new
这里我使用@Resource指定子类对象注入springboot管理
public class Factory {
@Resource(name = "AirportStaffImpl")
private MaintainTaskPeople airportStaffImpl;
@Resource(name = "SupervisorImpl")
private MaintainTaskPeople supervisorImpl;
@Resource(name = "RepairmanImpl")
private MaintainTaskPeople repairmanImpl;
public MaintainTaskPeople getMaintainTaskService(String roleNum){
if(roleNum.equals("1")){
return airportStaffImpl;
}else if(roleNum.equals("2")){
return supervisorImpl;
}else if(roleNum.equals("3")){
return repairmanImpl;
}
throw new ExceptionMsg("不存在的角色!");
}
}
注意:指定的impl实现类上面也要写上对应的@Service(“AirportStaffImpl”)
结尾:
这里简单用了设计模式,以便于后期的维护,使代码的各个关系比较清晰可见。