1. 單例模式
1.1. 使用場景
在前端開發中,全局狀態管理、配置信息、數據庫連接等往往需要在應用中只存在一個實例,避免多次實例化帶來的數據不一致性。例如,在一個前端應用中,全局的 loading 狀態通常需要一個單例模式來確保其唯一性。
1.2. 代碼實現
class Singleton {// 構造函數為私有,防止外部直接調用constructor() {if (Singleton.instance) {return Singleton.instance;}// 初始化其他屬性this.data = [];Singleton.instance = this;}// 靜態方法,獲取唯一的實例static getInstance() {if (!Singleton.instance) {Singleton.instance = new Singleton();}return Singleton.instance;}// 添加數據方法addData(item) {this.data.push(item);}// 獲取數據方法getData() {return this.data;}
}// 使用 Singleton
const instance1 = Singleton.getInstance();
instance1.addData('First Item');const instance2 = Singleton.getInstance();
console.log(instance2.getData()); // ['First Item'], instance1 和 instance2 是同一個實例
1.3.?詳細注釋
constructor():將構造函數私有化,通過判斷 Singleton.instance 是否已存在來確保單例。
getInstance():靜態方法用于獲取唯一實例,調用時如果實例不存在則創建新實例,存在則直接返回已有實例。
使用 addData 和 getData 方法演示單例模式下的數據存儲與獲取,保證所有調用的是同一個實例。
1.4.?實際應用
- 單例模式可用于前端中的全局配置對象、全局狀態管理(如 Redux Store)、全局事件總線等。
2. 工廠方法模式
2.1.?使用場景
當我們需要創建不同類型的對象但又不想在代碼中寫死實例化的邏輯時,工廠方法模式能夠根據條件動態生成合適的對象實例。在前端開發中,常用于根據不同配置生成相應的組件或對象。
2.2. 代碼實現
class Button {constructor(type) {this.type = type;}render() {console.log(`Render a ${this.type} button`);}
}class ButtonFactory {createButton(type) {switch (type) {case 'primary':return new Button('primary');case 'secondary':return new Button('secondary');default:throw new Error('Button type not supported');}}
}// 使用工廠方法
const factory = new ButtonFactory();
const primaryButton = factory.createButton('primary');
primaryButton.render(); // Render a primary button
2.3.?詳細注釋
Button:表示一個具體的按鈕對象,通過 type 來區分不同類型的按鈕。
ButtonFactory:工廠類用于創建不同類型的按鈕對象,提供了 createButton 方法,根據傳入的 type 動態生成對應的實例。
通過工廠方法來解耦實例化邏輯和對象使用,便于擴展。
2.4.?實際應用
- 工廠方法模式常用于創建復雜的對象實例,例如組件庫中的動態組件生成、API 服務實例化等。
3. 抽象工廠模式
3.1.?使用場景
當需要創建一組相關或相互依賴的對象時,抽象工廠模式能幫助我們統一創建流程。在前端框架中,常用于根據環境或用戶設置來創建不同的一組 UI 組件或工具。
3.2. 代碼實現
class MacButton {render() {console.log('Render a Mac button');}
}class WindowsButton {render() {console.log('Render a Windows button');}
}class MacFactory {createButton() {return new MacButton();}
}class WindowsFactory {createButton() {return new WindowsButton();}
}function createUI(factory) {const button = factory.createButton();button.render();
}// 使用抽象工廠
const macFactory = new MacFactory();
createUI(macFactory); // Render a Mac buttonconst windowsFactory = new WindowsFactory();
createUI(windowsFactory); // Render a Windows button
3.3.?詳細注釋
MacButton 與 WindowsButton:表示不同平臺下的按鈕組件。
MacFactory 與 WindowsFactory:各自負責創建相應平臺的組件,通過 createButton 方法創建相應的按鈕對象。
通過抽象工廠模式,確保了創建一整套相關聯對象的流程簡單統一。
3.4.?實際應用
抽象工廠模式廣泛用于創建跨平臺 UI 組件、表單控件等場景。
4. 建造者模式
4.1.?使用場景
當一個對象的創建需要依賴多個步驟或者多個部分時,建造者模式能通過逐步構建的方式來確保創建流程的清晰和可控。適合在前端復雜組件的創建中使用,例如動態表單、復雜配置對象等。
4.2. 代碼實現
class Form {constructor() {this.fields = [];}addField(field) {this.fields.push(field);}getForm() {return this.fields;}
}class FormBuilder {constructor() {this.form = new Form();}addTextField(label) {this.form.addField({ type: 'text', label });return this;}addCheckboxField(label) {this.form.addField({ type: 'checkbox', label });return this;}build() {return this.form;}
}// 使用建造者模式
const formBuilder = new FormBuilder();
const form = formBuilder.addTextField('Name').addCheckboxField('Subscribe').build();console.log(form.getForm()); // [{type: 'text', label: 'Name'}, {type: 'checkbox', label: 'Subscribe'}]
4.3.?詳細注釋
Form:表示表單對象,包含表單字段的數組。
FormBuilder:提供了一系列方法,用于動態添加表單字段,通過 build 方法返回構建好的表單。
通過建造者模式,可以靈活地構建復雜對象,同時保持代碼的簡潔和可讀性。
4.4.?實際應用
- 建造者模式常用于創建多步驟配置的對象,如復雜的 UI 組件、表單生成器、配置對象等。
5. 原型模式
5.1.?使用場景
當我們需要快速創建對象的副本時,原型模式可以通過拷貝已有對象來避免重復的初始化操作。常用于需要大量類似對象的場景,如渲染大量類似的 UI 組件或節點。
5.2. 代碼實現
class Prototype {constructor(data) {this.data = data;}clone() {return new Prototype(this.data);}
}// 使用原型模式
const original = new Prototype({ name: 'Original' });
const clone = original.clone();console.log(original.data); // { name: 'Original' }
console.log(clone.data); // { name: 'Original' }
console.log(original === clone); // false
5.3.?詳細注釋
Prototype:表示原型對象,提供了 clone 方法用于創建對象的副本。
clone():返回一個新對象,拷貝了原對象的數據,實現了對象的快速復制。
原型模式避免了重新創建和初始化對象的復雜性。
5.4.?實際應用
- 原型模式常用于需要大量創建相似對象的場景,如游戲開發中的對象克隆、前端應用中的組件渲染等。