概述
策略模式是一种行为设计模式,可用于定义一系列算法/实现并允许程序在运行时选择它们,Spring Plugin作为非常精简轻便的小规模插件系统,很好诠释了策略模式的实现。从官网得知,Spring Plugin是有史以来最小的插件,整个程序包只有十多个类,但却提供了Plugin接口实现的核心灵活性,满足构建模块化可扩展应用程序的要求。
原理
Spring Plugin提供一个Plugin接口提供后续继承使用声明,然后通过@EnablePluginRegistries注解依赖注入到Spring容器中,Spring容器会为我们自动匹配到插件的所有实现子对象,通过依赖注入,注入PluginRegistry对象获取拿到插件实例进行操作。
使用示例
1、添加maven依赖
<dependency> <groupId>org.springframework.plugin</groupId> <artifactId>spring-plugin-core</artifactId> <version>2.0.0.RELEASE</version></dependency>
2、定义接口参数对象
public class RuleContext { private String ruleCode; // ...}
3、定义接口
public interface RuleContextHandler extends Plugin<RuleContext> { void handle(RuleContext ruleContext);}
4、定义两个实现类
public class RuleStrategeAHandler implements RuleContextHandler {
@Override public void handle(RuleContext ruleContext) { // 规则策略A实现 }
}
public class RuleStrategeBHandler implements RuleContextHandler {
@Override public void handle(RuleContext ruleContext) { // 规则策略B实现 }
}
5、Spring启动类增加注解
@SpringBootApplication@EnablePluginRegistries({RuleContextHandler.class})public class Application {}
6、注入规则策略对象使用
public class RuleStrategeCaller { @Resource private PluginRegistry<RuleContextHandler, RuleContext> registry;
public void doRuleHanle(@RequestBody RuleContext ruleContext) { RuleContextHandler rh = registry.getRequiredPluginFor(ruleContext); rh.handle(ruleContext); }}
小结
Spring Plugin插件规模小,简单易用,虽然比较小众,但很好诠释了策略模式的实现,提供了Plugin接口实现的核心灵活性,满足构建模块化可扩展应用程序的要求,是实现典型策略模式的一大利器。