模板方法模式的定义:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
案例一:消息监听器
@Slf4j
public abstract class AbstractJsonStringMessageListener<T> implements MessageListener<String, String> {
protected abstract Class<T> jsonClass();
/**
* 处理转换为对象后的消息
*
* @param message 转换为对象后的消息
* @throws Exception
*/
protected abstract void handleMessage(T message) throws Exception;
@Override
public Action consume(ConsumerRecord<String, String> record, ConsumeContext context) {
log.info("Received message, record={}", record);
if (record == null || StringUtils.isEmpty(record.value())) {
return Action.DiscardInvalidMessage;
}
try {
T message = JSON.parseObject(record.value(), jsonClass());
handleMessage(message);
} catch (Exception e) {
log.error("Faild consuming message.", e);
return Action.CommitMessage;
}
return Action.CommitMessage;
}
}
子类实现
public class SwitchUpateMsgListener extends AbstractJsonStringMessageListener<SwitchUpateMsgData>
implements MessageListener<String, String> {
@Override
protected void handleMessage(SwitchUpateMsgData data) throws Exception {
//模板方法实现
}
}
案例二:以支付为例,先创建一个抽象类定义通用支付流程方法,然后为每种支付方式提供自己的具体操作
https://jingyan.baidu.com/article/fec7a1e5a259c61190b4e70c.html