java设计模式之策略模式的优雅实现

前言

策略模式是开发中常用的一种设计模式,主要解决在有多种算法相似的情况下,使用 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;
    }
}

上下文切换类:

@Component
public 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;
    }

}

测试:

@RestController
public class StrategyController {

    @Autowired
    private StrategyContext context;

    @RequestMapping("/method")
    public String method(Integer code) {
        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名称。

具体实现如下:

@Component
public 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上下文容器去管理,我们自己不需要再做实现了。实现方式如下:
@Component
public 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;来决定调用哪个实现类,这种适用于某一种场景的调用,无需聚合所有调用场景,如果想动态实现,推荐上面三种。策略模式的枚举类也可以用注解的方式实现,这里有兴趣的同学可以自己尝试一下。另外有其他更好的实现方式也可以在下方留言,大家一起学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值