场景:
有时候一个业务方法有多个实现类,需要根据特定的情形进行业务处理。
例如:商店支付,我们可以使用支付宝、微信扫描农行、xxx行的快捷支付(而不是微信支付、支付宝支付二维码)购买商品。
实现代码(代码和以上不相干,工作中实际使用的代码,供参考):
public interface ConvertService{ /*** * 转换 * @param request * @return */ ConversionResponse convert(ConversionRequest request); }
@Slf4j @Component("streamConveter") public class StreamConverter implements ConvertService { ... convert(ConversionRequest request) {} }
@Slf4j @Component("ttsConverter") public class TTSConverter extends WebSocketClient implements ConvertService{ public ConversionResponse convert(ConversionRequest request){ } }
class XXXImpl { @Autowired StreamConverter streamConverter; @Autowired TTSConverter wsConverter; @Autowired CacheService cacheService; private static ConversionResponse DefaultResponse = new ConversionResponse .Builder() .responseMessage("不支持该转换!") .responseCode(ResultCodes.ERROR) .uuid(null) .build(); public ConvertService doStrategy(ConversionMode mode) { ConvertService converter = null; switch (mode) { case TTS: converter = wsConverter; break; case ASR: converter = streamConverter; break; case Merge: } return converter; } public void xxx() { ConversionMode mode = request.getMode(); ConvertService converter = doStrategy(mode); if(Objects.isNull(converter)) { return DefaultResponse; } ConversionResponse response = converter.convert(request); if(response.getResponseCode() == ResultCodes.SUCCESS) { //如果执行成功,更新缓存 String hash = computeHash(request); String uuid = response.getUuid(); getCacheService().setCacheMap(CacheService.MEDIA_META,Collections.singletonMap(uuid,hash)); } return response; } }