1 策略模式demo
1.1 策略模式demo
搭建spring项目(策略类,策略子类,策略枚举,getBean工具类)
- 测试类:
package com.example.jiayou.ceshi.strategy; import org.springframework.stereotype.Controller; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.RequestMapping; /** * ErrorHandler * * @author 魏豆豆 * @date 2020/12/6 */ @Controller /** *@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解 */ @RequestMapping("/main") public class StrategyHandler { @RequestMapping("/strategy") public String strategy(String param){ System.out.println("aaa"); //demo1 son Strategy strategy = StrategyEnum.getStrategyById(param);//varible if(!ObjectUtils.isEmpty(strategy)){ return strategy.process(); } return "aaa"; } }
- 策略枚举
package com.example.jiayou.ceshi.strategy; import lombok.Getter; import org.apache.commons.lang.StringUtils; public enum StrategyEnum { AAA("AAA",SpringUtils.getBean(StrategyImplAAA.class),"aaa"); @Getter private String id; @Getter private Strategy strategy; @Getter private String remark; private StrategyEnum (String id,Strategy strategy,String remark){ this.id = id; this.strategy = strategy; this.remark = remark; } public static Strategy getStrategyById(String id){ if(StringUtils.isBlank(id)){ throw new NullPointerException("策略id"); } for(StrategyEnum strategyEnum : StrategyEnum.values()){ if(StringUtils.equals(id,strategyEnum.id)){ return strategyEnum.strategy; } } return null; } }
- 策略类
package com.example.jiayou.ceshi.strategy; import org.springframework.stereotype.Service; @Service public abstract class Strategy { public String process(){ System.out.println("parent"); return "parent"; } }
- 策略子类:
package com.example.jiayou.ceshi.strategy; import org.springframework.stereotype.Component; @Component public class StrategyImplAAA extends Strategy { public String process(){ System.out.println("childAAA"); return "AAA"; } }
- 新建getBean工具类
package com.example.jiayou.ceshi.strategy; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public class SpringUtils implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) { SpringUtils.context = applicationContext; } public static <T> T getBean(Class<T> clazz) { return context.getBean(clazz); } public static Object getBean(String name) { return context.getBean(name); } }
访问:
http://127.0.0.1:8080/main/strategy?param=AAA
诸葛