策略模式+工厂模式+Spring自动注入项目应用
1、策略接口类PaperResultStrategy
public interface PaperResultStrategy { AnswerReportDTO getResult(int projectId, int paperId); }
2、策略实现类PaperResultStrategyImpl2
@Component public class PaperResultStrategyImpl2 implements PaperResultStrategy { @Resource private AnswerMapper answerMapper; @Autowired private AnswerMapper answerMapper2; public PaperResultStrategyImpl2() { } @Override public AnswerReportDTO getResult(int projectId, int paperId) { List<AnswerDTO> pManResult = answerMapper.getPManResult(projectId, paperId); int finished = 0 ; if (pManResult.size() != 0) finished = 1; AnswerReportDTO reportDTO = new AnswerReportDTO("bar", pManResult, 1); return reportDTO; } }
3、策略注册枚举类PaperResultStrategyEnum
public enum PaperResultStrategyEnum { PM_MAN(2, "com.founderit.pmsaas.service.impl.PaperResultStrategyImpl2"), RISK_TOOL(17, "com.founderit.pmsaas.service.impl.PaperResultStrategyImpl17"); private Integer topicTypeId; private String className; PaperResultStrategyEnum(Integer topicTypeId, String className){ this.topicTypeId = topicTypeId; this.className = className; } public static String getClassName(Integer topicTypeId){ for (PaperResultStrategyEnum temp : PaperResultStrategyEnum.values()){ if (temp.getTopicTypeId() == topicTypeId) return temp.getClassName(); } return null; } public Integer getTopicTypeId() { return topicTypeId; } public void setTopicTypeId(Integer topicTypeId) { this.topicTypeId = topicTypeId; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } }
4、获取SpringBean容器的工具类SpringUtil
@Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; } } //获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通过name获取 Bean. public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } }
5、策略工厂类PaperResultStrategyFactory
通过工具类实现ApplicationContextAware获取策略实现类,可在策略实现类中使用自动注入;如果工厂模式使用Java反射机制,策略实现类不是Spring容器管理,成员变量自动注入为null。
@Component public class PaperResultStrategyFactory { public PaperResultStrategy getInstance(int topicTypeId) throws Exception { String className = PaperResultStrategyEnum.getClassName(topicTypeId); Class<?> aClass = ClassLoader.getSystemClassLoader().loadClass(className); PaperResultStrategy bean =(PaperResultStrategy) SpringUtil.getBean(aClass); System.out.println(bean.hashCode()); return bean; } }