💸 前言:被if-else支配的恐惧
场景还原:
老板:“小王,今天把微信支付接进来。”
小王:“好勒!” 于是写了一个pay()方法。
老板:“明天把支付宝也接进来。”
小王:“没问题!” 于是把pay()方法改成了:
if(channel==WECHAT){// 微信验签、调用、处理...}elseif(channel==ALIPAY){// 支付宝验签、调用、处理...}老板:“下周我们要出海,接一下 PayPal 和 Stripe。”
小王看着那坨已经 500 行的if-else代码,陷入了沉思……
这就是典型的“缺乏抽象能力”。
支付业务虽然通道不同,但核心流程是惊人一致的:
- 参数校验(Validate)
- 生成签名(Sign)
- 发送 HTTP 请求(Call API)
- 处理响应(Handle Response)
- 统一记录日志(Log)
针对这种**“流程固定,但细节不同”**的场景,模板方法模式就是唯一的真神。
🧠 核心原理:定义骨架,下放细节
模板方法模式的核心思想是:在父类中定义一个final的主流程方法(骨架),将具体的步骤延迟到子类去实现。
类图设计:
🛠️ 代码实战:重构支付网关
1. 定义抽象基类 (The Skeleton)
这是整个模式的灵魂。注意doPay方法必须是final的,防止子类篡改流程。
publicabstractclassAbstractPaymentChannel{// 核心模板方法:定义了支付的标准流程publicfinalPaymentResponsedoPay(PaymentRequestrequest){// 1. 通用日志logInfo("开始处理支付请求",request);// 2. 参数校验 (抽象步骤)if(!validate(request)){thrownewBizException("参数校验失败");}// 3. 加签 (抽象步骤)Stringsignature=sign(request);// 4. 调用三方接口 (抽象步骤)StringrawResponse=callApi(request,signature);// 5. 解析响应 (抽象步骤)PaymentResponseresponse=parseResponse(rawResponse);// 6. 通用后置处理postProcess(response);returnresponse;}// --- 抽象方法,强制子类实现 ---protectedabstractbooleanvalidate(PaymentRequestrequest);protectedabstractStringsign(PaymentRequestrequest);protectedabstractStringcallApi(PaymentRequestrequest,Stringsign);protectedabstractPaymentResponseparseResponse(StringrawResponse);// --- 通用方法,子类复用 ---privatevoidlogInfo(Stringmsg,Objectdata){// 统一的日志记录逻辑System.out.println(msg+": "+data);}// --- 钩子方法 (Hook),子类可选择性覆盖 ---protectedvoidpostProcess(PaymentResponseresponse){// 默认什么都不做}}2. 实现微信支付通道 (Concrete Class)
@ServicepublicclassWechatPaymentChannelextendsAbstractPaymentChannel{@Overrideprotectedbooleanvalidate(PaymentRequestrequest){System.out.println("✅ 微信渠道:校验 OpenID 是否必填");returnStringUtils.hasText(request.getExtra("openId"));}@OverrideprotectedStringsign(PaymentRequestrequest){System.out.println("🔑 微信渠道:使用 MD5 进行签名");returnSecureUtil.md5(request.toString());}@OverrideprotectedStringcallApi(PaymentRequestrequest,Stringsign){System.out.println("🚀 微信渠道:调用 https://api.mch.weixin.qq.com/...");return"<xml>...SUCCESS...</xml>";}@OverrideprotectedPaymentResponseparseResponse(StringrawResponse){System.out.println("📝 微信渠道:解析 XML 响应");returnnewPaymentResponse("SUCCESS","200");}}3. 实现支付宝通道 (Concrete Class)
@ServicepublicclassAlipayPaymentChannelextendsAbstractPaymentChannel{@Overrideprotectedbooleanvalidate(PaymentRequestrequest){System.out.println("✅ 支付宝渠道:校验 BuyerId");returntrue;}@OverrideprotectedStringsign(PaymentRequestrequest){System.out.println("🔑 支付宝渠道:使用 RSA2 进行签名");returnSecureUtil.rsa2(request.toString());}// ... 其他步骤实现}4. 配合工厂模式使用
最后,我们需要一个简单工厂 (Simple Factory)或者策略模式 (Strategy)的 Map 来分发请求。
@ComponentpublicclassPaymentChannelFactory{@AutowiredprivateMap<String,AbstractPaymentChannel>channelMap;publicAbstractPaymentChannelgetChannel(StringchannelCode){// channelMap 会自动注入所有 Bean,key 为 beanName// 例如:wechatPaymentChannel -> WechatPaymentChannelreturnchannelMap.get(channelCode+"PaymentChannel");}}💥 进阶技巧:钩子方法 (Hook) 的妙用
有时候,某个特定的渠道需要特殊的步骤。
比如:只有银联支付需要在支付完成后,发送短信通知用户。
我们不需要修改doPay主流程,只需要利用钩子方法。
在基类中:
// 默认为空实现protectedvoidpostProcess(PaymentResponseresponse){}在银联子类中:
@OverrideprotectedvoidpostProcess(PaymentResponseresponse){if("SUCCESS".equals(response.getStatus())){smsService.send("您的银联支付已成功!");}}这就是“开闭原则” (Open-Closed Principle) 的完美体现:对扩展开放,对修改关闭。
📝 总结
从if-else到模板方法模式,不仅仅是代码行数的变化,更是思维方式的跃迁。
- 复用性:公共逻辑(日志、异常处理、埋点)全部收敛在父类,改一处,所有通道生效。
- 扩展性:接新通道?新建一个类继承父类即可,老代码一行都不用动,测试风险极低。
- 规范性:父类通过
final关键字强制定义了业务的标准流程,新人想乱写都难。
写出机器能跑的代码是门槛,写出人能维护的代码才是本事。