定义策略接口(Strategy),里面定义需要执行的方法。
public interface Strategy {
void execute();
}
定义多个实现策略接口的类。
@Service("strategyOne")
public class ConcreteStrategyOne implements Strategy {
@Override
public void execute() {
System.out.println("执行策略一");
}
}
@Service("strategyTwo")
public class ConcreteStrategyTwo implements Strategy {
@Override
public void execute() {
System.out.println("执行策略二");
}
}
在使用策略的类中,通过@Autowired注解自动注入所有策略Bean。
- @Service注解标识的类实际上是一个Spring Bean,会由Spring IoC容器进行管理。
- 在Context类的构造函数中,使用@Autowired注解将Map类型的strategyMap参数自动注入。在程序启动时,Spring IoC容器会根据配置信息扫描所有实现了Strategy接口的Bean,将其装载到Map容器中,并通过Bean名称作为key,Bean对象作为value进行存储,所以可以直接通过bean名称来获取对应的bean。
- 在contextInterface方法中,根据传递的参数strategyType,即实现了Strategy接口的Bean的名称,从Map容器中获取对应的Bean对象。这里的get方法实际上是Map容器的get方法,在实现的时候使用了Java泛型,所以可以直接获取到对应的Bean对象。
- 获取到对应的Bean对象之后,直接调用其execute方法执行策略即可。
@Service
public class Context {
private final Map<String, Strategy> strategyMap;
@Autowired
public Context(Map<String, Strategy> strategyMap) {
this.strategyMap = strategyMap;
}
public void contextInterface(String strategyType) {
Strategy strategy = strategyMap.get(strategyType);
strategy.execute();
}
}
在Context类的构造函数中,通过@Autowired和Map类型的参数将所有实现策略接口的Bean自动注入。在contextInterface方法中,根据传递的参数获取对应的策略对象,并执行其execute方法。
在Spring配置文件中,通过context:component-scan指定扫描Context和各个实现策略接口的类所在的包。
<context:component-scan base-package="com.example.strategy" />
这样,在使用时就可以直接调用Context类的contextInterface方法,并传入实现Strategy接口的Bean名称作为参数。
@Autowired
private Context context;
// 执行策略一
context.contextInterface("strategyOne");
// 执行策略二
context.contextInterface("strategyTwo");
这样就可以实现基于Spring注解的策略模式了,避免了使用if判断语句,使代码更加优雅和易于维护。