java设计模式之策略模式的优雅实现_zhaojun20161206的博客-CSDN博客

前言

策略模式是开发中常用的一种设计模式,主要解决在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护的问题。看了网上很多关于策略模式的上下文切换类实现都不甚优雅,故而想总结分享一篇自我感觉比较优雅的处理方式,方便大家一起学习。

方式一:使用@PostConstruct初始化到map中

该方式是比较常用的,相对比较优雅,能满足动态获取不同实现类的功能。废话不多说直接上代码。

策略类:

public interface Strategy {    /**     * 策略方法     */    void method();}

策略实现类:

@Service(value = "strategyA")public class StrategyA implements Strategy {    /**     * 策略方法     */    @Override    public void method() {        System.out.println("我是A策略实现方案!");    }}  @Service(value = "strategyB")public class StrategyB implements Strategy {    /**     * 策略方法     */    @Override    public void method() {        System.out.println("我是B策略实现方案!");    } @Service(value = "strategyC")public class StrategyC implements Strategy {    /**     * 策略方法     */    @Override    public void method() {        System.out.println("我是C策略实现方案!");    }}

枚举类:

public enum StrategyEnum {    /**     * 策略枚举类     */    STRATEGY_A(1, "strategyA"),    STRATEGY_B(2, "strategyB"),    STRATEGY_C(3, "strategyC");     private Integer code;     private String name;     StrategyEnum(Integer code, String name) {        this.code = code;        this.name = name;    }     public static StrategyEnum getByCode(Integer code) {        StrategyEnum[] values = StrategyEnum.values();        for (StrategyEnum strategyEnum : values) {            if (strategyEnum.getCode().equals(code)) {                return strategyEnum;            }        }        return null;    }     /**     * Getter method for property <tt>code</tt>.     *     * @return property value of code     */    public Integer getCode() {        return code;    }     /**     * Getter method for property <tt>name</tt>.     *     * @return property value of name     */    public String getName() {        return name;    }}

上下文切换类:

@Componentpublic class StrategyContext {    private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>();    @Autowired    private ApplicationContext applicationContext;     @PostConstruct    private void init() {        strategyMap.putAll(applicationContext.getBeansOfType(Strategy.class));    }         public Strategy getInstance(Integer code) {        String beanName = StrategyEnum.getByCode(code).getName();        return this.getInstanceByBeanName(beanName);    }     private Strategy getInstanceByBeanName(String beanName) {        if (!StringUtils.isEmpty(beanName)) {            return strategyMap.get(beanName);        }        return null;    } }

测试:

@RestControllerpublic class StrategyController {     @Autowired    private StrategyContext context;     @RequestMapping("/method")    public String method() {        return context.getInstance(code).method();    }

测试结果:

方式二:使用@Autowired初始化到map中

原因是:@Autowired 注释中提到In case of a java.util.Collection or java.util.Map dependency type, the container will autowire all beans matching the declared value type. In case of a Map, the keys must be declared as type String and will be resolved to the corresponding bean names.

意思是:以java.util.Collection 或java.util.Map 为例。映射依赖项类型,容器将自动连接所有与声明值类型匹配的bean。对于映射,键必须声明为类型String,并将解析为相应的bean名称。

具体实现如下:

@Componentpublic class StrategyContext {    private final Map<String, Strategy> strategyMap = new ConcurrentHashMap<>();         @Autowired    public StrategyContext(Map<String, Strategy> strategyMap) {        this.strategyMap.clear();        strategyMap.forEach((k, v) -> this.strategyMap.put(k, v));    }     public Strategy getInstance(Integer code) {        String beanName = StrategyEnum.getByCode(code).getName();        return this.getInstanceByBeanName(beanName);    }     private Strategy getInstanceByBeanName(String beanName) {        if (!StringUtils.isEmpty(beanName)) {            return strategyMap.get(beanName);        }        return null;    }}

测试结果同方式一,这里就不演示了。

方式三:使用ApplicationContext

这是交给spring上下文容器去管理,我们自己不需要再做实现了。实现方式如下:
@Componentpublic class StrategyContext {        @Autowired    private ApplicationContext applicationContext;     public Strategy getInstance(Integer code) {        String beanName = StrategyEnum.getByCode(code).getName();        return this.getInstanceByBeanName(beanName);    }          private Strategy getInstanceByBeanName(String beanName) {        if (!StringUtils.isEmpty(beanName)) {            return (Strategy) applicationContext.getBean(beanName);        }        return null;    }  }

其实这种方式和第二种差不多,第二种也是借助spring,但是不同点是未进行缓存,从beanFactory中获取。测试结果同方式一,这里不再演示了。

总结:

这三种动态获取策略实现类的方法,个人觉得大同小异,都是通过实现类beanName实现动态的效果,其实还有一种比较简单的方式就是通过注解@Qualifier(value = "strategyA")+@Autowired private Strategy strategy;来决定调用哪个实现类,这种适用于某一种场景的调用,无需聚合所有调用场景,如果想动态实现,推荐上面三种。策略模式的枚举类也可以用注解的方式实现,这里有兴趣的同学可以自己尝试一下。另外有其他更好的实现方式也可以在下方留言,大家一起学习。


原网址: 访问
创建于: 2021-03-11 18:50:10
目录: default
标签: 无

请先后发表评论
  • 最新评论
  • 总共0条评论