本文將帶來最實(shí)用的 8 種設(shè)計(jì)模式及其典型應(yīng)用場(chǎng)景!一、模塊模式(Module Pattern)
核心思想:
const Counter = (function () { let count = 0;
return { increment() { count++; }, getCount() { return count; }, };})();
Counter.increment();console.log(Counter.getCount());
二、工廠模式(Factory Pattern)
核心思想:
class Button { constructor(text, color) { this.text = text; this.color = color; }}
function createButton(type) { switch (type) { case 'primary': return new Button('Submit', 'blue'); case 'danger': return new Button('Delete', 'red'); default: return new Button('Button', 'gray'); }}
const btn = createButton('primary');
三、單例模式(Singleton Pattern)
核心思想:
class Logger { constructor() { if (!Logger.instance) { this.logs = []; Logger.instance = this; } return Logger.instance; }
log(message) { this.logs.push(message); console.log(message); }}
const logger1 = new Logger();const logger2 = new Logger();console.log(logger1 === logger2);
四、觀察者模式(Observer Pattern)
核心思想:
class EventEmitter { constructor() { this.events = {}; }
on(event, listener) { if (!this.events[event]) { this.events[event] = []; } this.events[event].push(listener); }
emit(event, ...args) { if (this.events[event]) { this.events[event].forEach(listener => listener(...args)); } }}
const emitter = new EventEmitter();emitter.on('data', (data) => console.log('Received:', data));emitter.emit('data', { id: 1 });
五、代理模式(Proxy Pattern)
核心思想:
const user = { name: 'John', age: 30};
const validatorProxy = new Proxy(user, { set(target, prop, value) { if (prop === 'age' && typeof value !== 'number') { throw new Error('Age must be a number'); } target[prop] = value; return true; }});
validatorProxy.age = '30';
六、裝飾器模式(Decorator Pattern)
核心思想:
function logDecorator(target, name, descriptor) { const original = descriptor.value; descriptor.value = function (...args) { console.log(`Calling ${name} with args:`, args); return original.apply(this, args); }; return descriptor;}
class Calculator { @logDecorator add(a, b) { return a + b; }}
const calc = new Calculator();calc.add(2, 3);
七、策略模式(Strategy Pattern)
核心思想:
const strategies = { add: (a, b) => a + b, subtract: (a, b) => a - b, multiply: (a, b) => a * b,};
function calculate(strategy, a, b) { return strategies[strategy](a, b);}
console.log(calculate('multiply', 3, 4));
八、組合模式(Composite Pattern)
核心思想:
class MenuItem { constructor(name) { this.name = name; }
display() { console.log(`Menu Item: ${this.name}`); }}
class Menu { constructor(name) { this.name = name; this.children = []; }
add(child) { this.children.push(child); }
display() { console.log(`Menu: ${this.name}`); this.children.forEach(child => child.display()); }}
const rootMenu = new Menu('Root');rootMenu.add(new MenuItem('Home'));const subMenu = new Menu('Settings');subMenu.add(new MenuItem('Profile'));rootMenu.add(subMenu);rootMenu.display();
如何選擇設(shè)計(jì)模式?
優(yōu)先解決問題:不要為了用模式而用模式。
關(guān)注代碼可維護(hù)性:模式應(yīng)減少耦合,增強(qiáng)擴(kuò)展性。
結(jié)合語言特性:JavaScript 適合函數(shù)式與原型鏈,靈活運(yùn)用閉包和高階函數(shù)。
框架生態(tài)參考:如 React 的 Hooks、Vue 的 Composition API 已內(nèi)置模式思想。
?
總結(jié)
| | |
|---|
| | |
| | 動(dòng)態(tài)生成對(duì)象、屏蔽構(gòu)造細(xì)節(jié) |
| | |
| | |
| | |
| | 日志增強(qiáng)、權(quán)限校驗(yàn) |
| | |
| | |
核心原則:理解模式背后的設(shè)計(jì)思想(如解耦、復(fù)用、擴(kuò)展),比死記代碼更重要。
閱讀原文:原文鏈接
該文章在 2025/4/23 10:12:39 編輯過