策略模式1
package com.cmit.budget.strategy; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Component; import java.util.Map; /** * @author lyc * @ClassName OrderContextStrategy * @Description TODO * @date 2023/3/21 14:51 */ @Component public class OrderContextStrategy { public static OrderGenerateStrategy getInstance(String commandType) { //此处我采用enum 也可以采用其他方式去实现 OrderGenerateStrategy orderGenerateStrategy = null; Map<String, String> allClazz = OrderFilter.getAllClazz(); String clazz = allClazz.get(commandType.trim().toLowerCase()); if (StringUtils.isNoneEmpty(clazz)) { try { //调用无参构造器创建实例 orderGenerateStrategy = (OrderGenerateStrategy) Class.forName(clazz).newInstance(); } catch (Exception e) { e.printStackTrace(); } } return orderGenerateStrategy; } }
package com.cmit.budget.strategy; /** * @author lyc * @ClassName OrderAAAStrategyImpl * @Description TODO * @date 2023/3/21 14:55 */ public class OrderAAAStrategyImpl implements OrderGenerateStrategy { @Override public boolean orderGeneration(String type) { return false; } }
package com.cmit.budget.strategy; /** * @author lyc * @ClassName OrderGoodStrategyImpl * @Description TODO * @date 2023/3/21 14:56 */ public class OrderGoodStrategyImpl implements OrderGenerateStrategy{ @Override public boolean orderGeneration(String type) { return false; } }
package com.cmit.budget.strategy; import java.util.HashMap; import java.util.Map; /** * @author lyc * @ClassName OrderFilter * @Description TODO * @date 2023/3/21 14:56 */ public enum OrderFilter { ORDER_FILTER_NINE("9", "com.cmit.budget.strategy.OrderAAAStrategyImpl"), /** * GOOD */ ORDER_FILTER_GOOD_COMPANY("23", "com.cmit.budget.strategy.OrderGoodStrategyImpl"); private String className; private String command; public String getCommand() { return command; } public void setCommand(String command) { this.command = command; } public static Map<String, String> getAllClazz() { Map<String, String> map = new HashMap<>(); for (OrderFilter commandEnum : OrderFilter.values()) { map.put(commandEnum.getCommand(), commandEnum.getClassName()); } return map; } OrderFilter(String command, String className) { this.setCommand(command); this.setClassName(className); } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } }
package com.cmit.budget.strategy; /** * @author lyc * @ClassName test * @Description TODO * @date 2023/3/21 14:59 */ public class test { public static void main(String[] args) { OrderGenerateStrategy instance = OrderContextStrategy.getInstance("9"); boolean b = instance.orderGeneration(""); } }
package com.cmit.budget.strategy; /** * @author lyc * @ClassName OrderGenerateStrategy * @Description TODO * @date 2023/3/21 14:52 */ public interface OrderGenerateStrategy { boolean orderGeneration(String type); }
作者:http://cnblogs.com/lyc-code/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权力。