项目中用到的策略模式+工厂模式
spring中的整合
接口
package com.example.demo.model; import org.springframework.beans.factory.InitializingBean; public interface Handler extends InitializingBean { public void aaa(String name); }
工厂;
package com.example.demo.impl; import com.example.demo.model.Handler; import org.springframework.util.StringUtils; import java.util.HashMap; import java.util.Map; public class DemoFactory { private static Map<String, Handler> stringHandlerMap = new HashMap<>(); public static Handler getInvokeStrateg(String name){ return stringHandlerMap.get(name); } public static void register(String name,Handler handler){ if(StringUtils.isEmpty(name) || null == handler){ return; } stringHandlerMap.put(name,handler); } }
实现:
package com.example.demo.impl; import com.example.demo.model.Handler; import org.springframework.stereotype.Component; @Component public class DemoHandler implements Handler { @Override public void aaa(String name) { System.out.println(name +"demoHandler....."); } @Override public void afterPropertiesSet() throws Exception { DemoFactory.register("dd",this); } }
springboot整合
接口:
public interface ReportHandler { String getResult(); }
实现类;
@Component(value = "A1") public class ReportHandlerA1 implements ReportHandler { @Override public String getResult() { return "我是A1"; } }
工厂;
@Service public class ReportFactory { /** * 初始化的时候将所有的ReportHandler自动加载到Map中 */ @Autowired private final Map<String, ReportHandler> reportIns = new ConcurrentHashMap<>(); public ReportHandler getReportIns(String code) { ReportHandler reportInstance = reportIns.get(code); if (reportInstance == null) { throw new RuntimeException("未定义reportInstance"); } return reportInstance; } }
不用工厂;
@Service public class ReportFactory { public ReportHandler getReportIns(String code) { //cn.hutool.extra.spring.SpringUtil; return SpringUtil.getBean(providerCode); } }
验证;
@RestController public class control { @Autowired private ReportFactory factory; // 使用注解注入 @GetMapping("/drawMyShape") public String drawMyShape(){ shapeBeanFactoryDraw(); return "成功"; } private void shapeBeanFactoryDraw() { System.out.println("======= 实现二Factory ======="); ReportHandler rh= factory.getReportIns("A1"); rh.getResult(); }