一、模式核心理解
模板方法模式是一種??行為設計模式??,通過定義算法骨架并允許子類重寫特定步驟來實現代碼復用。
如同建筑圖紙規定房屋結構,具體裝修由業主決定,該模式適用于??固定流程中需要靈活擴展??的場景。
// 基礎請求處理類(模板)
class BaseRequestHandler {// 模板方法(禁止override)async execute() {this.validateParams();const processed = await this.processRequest();this.afterProcess();return this.createResponse(processed);}validateParams() {throw new Error("必須實現參數校驗方法");}// 鉤子方法(可選實現)afterProcess() {}
}// 具體API請求實現
class UserAPIHandler extends BaseRequestHandler {validateParams() {if (!this.params.userId) throw "用戶ID必填";}async processRequest() {return await fetch(`/users/${this.params.userId}`);}createResponse(data) {return { status: 200, data };}
}// 使用示例
const handler = new UserAPIHandler({ userId: 123 });
handler.execute();
二、典型應用場景
1. 框架生命周期控制
// React類組件示例
class BaseComponent extends React.Component {// 模板方法componentDidMount() {this.initState();this.fetchData();this.bindEvents();}initState() {} // 子類實現fetchData() {} // 子類實現bindEvents() {} // 默認空實現(鉤子方法)
}class UserList extends BaseComponent {initState() {this.setState({ users: [] });}fetchData() {axios.get('/api/users').then(res => this.setState({ users: res.data }));}
}
2. 表單校驗系統
class FormValidator {validate(formData) {this.checkRequiredFields(formData);const customResult = this.customValidation(formData);return this.formatResult(customResult);}checkRequiredFields(formData) {// 通用必填校驗邏輯}customValidation() {throw new Error("必須實現具體校驗規則");}formatResult(result) {return { isValid: result, timestamp: Date.now() };}
}class LoginFormValidator extends FormValidator {customValidation(formData) {return formData.password.length >= 8;}
}
三、使用建議
- ??流程標準化??:支付流程(風控檢查->創建訂單->調用支付->結果處理)
class PaymentProcessor {async pay(amount) {this.riskCheck();const order = this.createOrder(amount);const result = await this.callPaymentGateway(order);return this.handleResult(result);}// ...抽象方法聲明
}
- ??合理使用鉤子??:在報表生成器中設置可選步驟
class ReportGenerator {generate() {this.fetchData();this.beforeRender(); // 鉤子方法this.renderHeader();this.renderBody();}beforeRender() {} // 默認空實現
}
- ??組合優于繼承??:對于復雜場景建議使用策略模式+模板方法
class DataExporter {constructor(formatter) {this.formatter = formatter;}export() {const raw = this.getData();return this.formatter(raw);}
}
四、注意事項
- ??避免流程碎片化??(錯誤示例)
// 反模式:過度拆分步驟
class BadTemplate {execute() {this.step1();this.step2();this.step3();this.step4();// 20+步驟...}
}
- ??子類責任邊界??
class OrderProcessor extends BaseProcessor {validate() {// 不要修改執行順序super.validate(); // 必須調用父類方法this.checkInventory(); // 擴展校驗}
}
- ??模板方法凍結??
class SecureBase {execute() {Object.freeze(this.execute); // 防止子類重寫模板方法// ...執行流程}
}
五、總結
模板方法模式在前端開發中適合處理??流程固定但實現可變??的場景,如請求處理、表單校驗、生命周期管理等。使用時要注意:
- 保持模板方法穩定,通過鉤子方法擴展
- 子類實現不超過3層繼承
- 復雜場景結合策略模式使用
- 使用TypeScript時聲明抽象方法
// TypeScript實現示例
abstract class UIComponent {abstract render(): void;mount() {this.willMount();this.render();this.didMount();}protected willMount() {}protected didMount() {}
}
正確使用模板方法模式可以提升代碼復用率30%以上,但需根據實際場景靈活選擇實現方式。
在微前端架構中,該模式常用于基座應用與子應用的生命周期管理,建議結合具體業務需求進行合理設計。