策略模式+spring框架
spring+策略模式:https://www.cnblogs.com/z-qinfeng/p/12210665.html
以上实现有点复杂,使用了自定义标签以及postProcessor,反射等等。
Spring框架下使用策略模式:https://blog.csdn.net/guandongsheng110/article/details/116266249
此文章思路清晰:https://zhuanlan.zhihu.com/p/102812484
总结一下,
- spring中使用策略模式,最主要是利用spring的自动映射@Autowired,自动映射出List<xxxInterface>;
下图是简单的策略模式:
上图中,在ChannelHandler中使用@Autowired标签使得List<Channel>自动映射;getChannel(xxx);则根据传入的策略标识,调用channel.match();匹配到合适的channel,【一般来说传入的条件是代码中的if判断的条件,如果判断条件较为复杂,那么建议封装成一个类】;
客户端不直接对接Channel,而是与ChannelHandler对接。
Channel接口的match();其实也可以返回一个数值,如果后续代码需要使用到该接口的标识。
- Spring其实不止可以自动映射出List<Interface>;还可以映射出Map<String,Interface>,其中String为该Bean的名字;
可以通过@Service("XXX")来自定义Map key的数值,也可以通过@PostConstruct来实现
interface Channel{
String getCode();
void pay();
}
@Component
class RoutingService {
private Map<String, Channel> routeMap = new HashMap<>();
@Autowired
private List<Channel> channelList;
@PostConstruct
void init() {
initRoutingRules();
}
private void initRoutingRules() {
for (Channel channel : channelList) {
routeMap.put(channel.getCode(), channel);
}
}
public Channel route(String strategy) {
Channel channel;
channel = routeMap.get(strategy);
if (channel == null) {
//return null;
//throw
}
return channel;
}
}
这就稍微涉及Spring初始化,第一个链接中也使用了对应的方法,此处需要补一下spring初始化知识~
PS:这只是个简易的策略模式模型,实际使用中需要根据业务做相应的转变,例如channel.pay();需要加入参数与返回值,etc...
至此,策略模式+spring完结,撒花✿✿ヽ(°▽°)ノ✿