1.概述
本篇文章主要会描述SpringBoot与策略模式的结合使用,因为不涉及到理论部分,所以在阅读本篇之前,需要对策略模式的理论已经有了一个基本的了解。
1.1.简述策略模式
策略模式有3种角色,分别为:选择器、抽象策略、策略实例。
其中选择器selector又被称为上下文context,其作用为通过不同的标识来获取对应的策略实例。策略实例就是封装不同算法的实例对象,而抽象策略就是策略实例的顶层接口。
2.实现方法
我们在学习设计模式的时候会发现在各类模式中的类与对象都是手动创建的,而在日常的开发中,我们往往会将对象的生命周期交给Spring管理,也就是说,需要我们自行将各类bean
组合成一个可运行的设计模式。
3.代码实现
3.1 编写枚举类
public enum ContentType {
A, B
}
3.2 编写工厂类
public interface ChannelFactory {
IChannelService getChannel(ContentType contentType);
}
3.3 使用Bean注册工厂
@Configuration
public class ChannelConfig {
@Bean("ChannelFactory")
public FactoryBean serviceLocatorFactoryBean() {
ServiceLocatorFactoryBean factoryBean = new ServiceLocatorFactoryBean();
factoryBean.setServiceLocatorInterface(ChannelFactory.class);
return factoryBean;
}
}
3.4 编写Controller
@Resource
private ChannelFactory channelFactory;
@GetMapping("/test01")
public Result getTest01() {
channelFactory.getChannel(ContentType.A).handle();
return Result.success("OK");
}
3.5 编写Service
public interface IChannelService {
void handle();
}
3.6编写Service实现类
@Service("A")
public class AChannelServiceImpl implements IChannelService {
@Override
public void handle() {
System.out.println("A");
}
}
@Service("B")
public class BChannelServiceImpl implements IChannelService {
@Override
public void handle() {
System.out.println("B");
}
}