# 前端常見設計模式深度解析
一、設計模式概述
設計模式是解決特定問題的經驗總結,前端開發中常用的設計模式可分為三大類:
- 創建型模式:處理對象創建機制(單例、工廠等)
- 結構型模式:處理對象組合(裝飾器、適配器等)
- 行為型模式:處理對象間通信(觀察者、策略等)
二、核心設計模式詳解
1. 單例模式(Singleton)
現代實現方案
const Singleton = (() => {let instance;function createInstance() {return {data: [],add(item) {this.data.push(item);},get() {return [...this.data];}};}return {getInstance() {if (!instance) {instance = createInstance();}return instance;}};
})();// 使用示例
const store1 = Singleton.getInstance();
const store2 = Singleton.getInstance();
console.log(store1 === store2); // true#### 應用場景
- Redux/Vuex的store管理
- 全局緩存對象
- 瀏覽器全局對象(如window)### 2. 觀察者模式(Observer)
#### 增強版實現
```javascript
class EventBus {constructor() {this.events = new Map();}on(event, callback, once = false) {if (!this.events.has(event)) {this.events.set(event, new Set());}this.events.get(event).add({ callback, once });}once(event, callback) {this.on(event, callback, true);}emit(event, ...args) {if (!this.events.has(event)) return;const handlers = this.events.get(event);handlers.forEach(handler => {handler.callback(...args);if (handler.once) {this.off(event, handler.callback);}});}off(event, callback) {if (!this.events.has(event)) return;const handlers = this.events.get(event);for (let handler of handlers) {if (handler.callback === callback) {handlers.delete(handler);break;}}}
}// 使用示例
const bus = new EventBus();
bus.on('login', user => console.log(`User ${user.name} logged in`));
bus.emit('login', { name: 'Alice' });
實際應用
- Vue的EventBus
- DOM事件系統
- WebSocket消息處理
3. 工廠模式(Factory)
現代變體
interface Product {operation(): string;
}class ConcreteProductA implements Product {operation() {return 'Product A';}
}class ConcreteProductB implements Product {operation() {return 'Product B';}
}class ProductFactory {static createProduct(type: 'A' | 'B'): Product {switch (type) {case 'A': return new ConcreteProductA();case 'B': return new ConcreteProductB();default: throw new Error('Invalid product type');}}
}// 使用示例
const product = ProductFactory.createProduct('A');
console.log(product.operation()); // "Product A"
應用場景
- UI組件庫(Button、Modal等)
- 不同環境配置(開發/生產)
- API客戶端(REST/GraphQL切換)
三、其他重要設計模式
1. 策略模式(Strategy)
const strategies = {add: (a, b) => a + b,subtract: (a, b) => a - b,multiply: (a, b) => a * b
};class Calculator {execute(strategy, a, b) {return strategies[strategy]?.(a, b) ?? NaN;}
}// 使用示例
const calc = new Calculator();
console.log(calc.execute('add', 5, 3)); // 8
2. 裝飾器模式(Decorator)
function withLogging(fn) {return function(...args) {console.log(`Calling ${fn.name} with`, args);const result = fn.apply(this, args);console.log(`Result:`, result);return result;};
}// 使用示例
const add = withLogging((a, b) => a + b);
add(2, 3);
// 輸出:
// Calling add with [2, 3]
// Result: 5
3. 代理模式(Proxy)
const apiProxy = new Proxy({}, {get(target, endpoint) {return async (params) => {console.log(`Calling API: /${endpoint}`);const res = await fetch(`https://api.example.com/${endpoint}`, {method: 'POST',body: JSON.stringify(params)});return res.json();};}
});// 使用示例
const data = await apiProxy.users({ page: 1 });
四、設計模式在前端框架中的應用
設計模式 | React應用場景 | Vue應用場景 |
---|---|---|
觀察者模式 | Context API | EventBus |
策略模式 | Hooks自定義邏輯 | 組件方法 |
裝飾器模式 | HOC高階組件 | 裝飾器語法 |
代理模式 | ForwardRef | 計算屬性 |
工廠模式 | createElement | 組件工廠 |
五、設計模式選擇指南
-
何時使用單例模式:
- 需要全局唯一狀態時
- 頻繁訪問的共享資源
- 避免重復初始化開銷
-
何時使用觀察者模式:
- 組件間松耦合通信
- 實時數據更新場景
- 跨層級組件交互
-
何時使用工廠模式:
- 創建過程復雜時
- 需要根據不同條件創建不同實例
- 需要隱藏創建細節
六、性能與注意事項
-
單例模式:
- 注意內存泄漏問題
- 考慮線程安全(在Web Worker場景)
-
觀察者模式:
- 及時取消訂閱
- 避免過度通知導致的性能問題
-
工廠模式:
- 不要過度設計簡單對象創建
- 考慮與依賴注入結合使用
七、現代JavaScript中的新模式
- 組合模式(Composition):
const canFly = {fly() {console.log('Flying!');}
};const canSwim = {swim() {console.log('Swimming!');}
};function createFlyingFish() {return Object.assign({}, canFly, canSwim);
}
- 模塊模式(Module):
// ES Modules
export const api = {get() { /* ... */ },post() { /* ... */ }
};// 或使用IIFE
const counter = (() => {let count = 0;return {increment() { count++ },get() { return count }};
})();
掌握這些設計模式能顯著提升代碼質量,建議在實際項目中:
- 從簡單模式開始應用
- 逐步嘗試復雜模式組合
- 根據項目規模選擇適當模式
- 避免過度設計簡單場景