第一步:创建一个接口继承 InitializingBean
public interface IStrategy extends InitializingBean {
public Boolean executeConsumer();
}
第二步:创建工厂方法
public class ContextFactory {
private static final HashMap<String, IStrategy> contextMap = new HashMap<>();
/**
*
* 注册
* @param name 策略名称
* @param strategy 策略类
*/
public static void register(String name, IStrategy strategy){
if (StringUtils.isEmpty(name) || Objects.isNull(strategy)) {
return;
}
contextMap.put(name, strategy);
}
/**
* 根据name获取对应的contextMap实现
*
* @param name 策略名称
* @return
*/
public static IStrategy getInvokeStrategyMap(String name) {
Assert.isFalse(StringUtils.isBlank(name), "策略名称不能为空!");
Assert.isFalse(Objects.isNull(contextMap.get(name)), "未找到对应的策略实现!");
return contextMap.get(name);
}
}
第三步:写实现类
@Slf4j
@Service
@RequiredArgsConstructor
public class HospitalizedAssessStrategyImpl implements IStrategy {
/**
* 生成对应的策略名称
*/
@Override
public void afterPropertiesSet() {
ContextFactory.register( "入院评估",this);
}
@Override
public Boolean executeConsumer() {
System.out.println("测试策略!");
return null;
}
}
第四步:调用
@Override
protected boolean doExecuteBusiness(MessageExt messageExt) {
String message = getMessageBody(messageExt);
log.info("主题:{},收到消息:{},msgId:{}", messageExt.getTopic(), message, messageExt.getMsgId());
//新增入院评估
IStrategy strategy = ContextFactory.getInvokeStrategyMap("入院评估");
strategy.executeConsumer();
return true;
}