拒绝多种if else,(springboot版本实现)
在我们工作当中,如果写多个if else 看起来是比较费事的,毕竟如果一段代码中出现很长代码段,就已经很不容易维护
spring+工厂模式实现
核心代码
@Component public class ProductStrategyFactory { /** * 使用依赖注入引入 ProductService 产品实现类,以 Bean 名称作为 Map 的 Key,以 Bean 实现类作为 Value */ @Resource private Map<String, testService> strategyMap = new ConcurrentHashMap<>(3); /** * 查找对应的产品的处理策略 * * @param productName 产品名称 * @return 对应的产品订购逻辑实现策略 */ public testService getProductStrategy(String productName) { // 根据从 productName 从 strategyMap 集合中查询对应的产品下单策略 return strategyMap.get(productName); } }
测试工厂
public interface testService { void sayhello(String str); }
测试工厂1
@Service("test1") @RequiredArgsConstructor public class test1serviceImpl implements testService { final TestMapper testMapper; @Override public void sayhello(String str) { System.out.println(" hello... "+str); } }
测试工厂2
@Service("test2") @RequiredArgsConstructor public class test2serviceImpl implements testService { final TestMapper testMapper; @Override public void sayhello(String str) { System.out.println(" hello... "+str); } }
测试工厂3
@Service("test3") @RequiredArgsConstructor public class test3serviceImpl implements testService { final TestMapper testMapper; @Override public void sayhello(String str) { System.out.println(" hello... "+str); } }
测试controller
@GetMapping("test") public ResponseEntity sayhello(String str){ testService productStrategy = productStrategyFactory.getProductStrategy(str); productStrategy.sayhello(str); return ResponseEntity.noContent().build(); }
能跑就行
下一篇:
浏览器视频文件分段缓存合并成完整的视频