1、單例開發模式(Singleton Pattern)
單例模式是一種創建型設計模式,目的是確保在程序運行期間,某個類只有一個實例,并提供一個全局訪問點來訪問該實例。
核心特點
- 唯一實例:一個類只能創建一個對象實例。
- 全局訪問:通過一個靜態方法或變量來訪問該實例。
- 延遲初始化:實例通常在第一次使用時才會被創建(懶加載)。
class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;}showMessage() {console.log("This is a singleton!");}
}const instance1 = new Singleton();
const instance2 = new Singleton();console.log(instance1 === instance2); // true
2、工廠模式(Factory Pattern)
特點
- 通過一個工廠方法創建對象,而不是直接使用
new
操作符。 - 子類可以通過工廠方法決定實例化的具體類。
適用場景
- 創建復雜對象時,希望隱藏其創建細節。
- 需要在運行時動態確定創建哪種對象。
class Product {constructor(name) {this.name = name;}
}class ProductFactory {static createProduct(type) {if (type === "A") {return new Product("Product A");} else if (type === "B") {return new Product("Product B");} else {throw new Error("Unknown product type");}}
}const productA = ProductFactory.createProduct("A");
console.log(productA.name); // Product A
3、觀察者模式(Observer Pattern)
特點
- 定義對象間的一對多依賴關系。
- 當一個對象的狀態改變時,所有依賴者都會收到通知并更新。
適用場景
- 事件驅動的系統,例如 UI 事件監聽。
- 多個模塊需要同步某個數據的變化。
class Subject {constructor() {this.observers = [];}addObserver(observer) {this.observers.push(observer);}notifyObservers(data) {this.observers.forEach((observer) => observer.update(data));}
}class Observer {update(data) {console.log("Observer received:", data);}
}const subject = new Subject();
const observer1 = new Observer();
const observer2 = new Observer();subject.addObserver(observer1);
subject.addObserver(observer2);subject.notifyObservers("Hello Observers!"); // All observers will log the message
4、策略模式(Strategy Pattern)
特點
- 定義一系列算法,將它們封裝成獨立的策略類,并使它們可以互換。
- 避免了使用大量
if-else
或switch
語句。
適用場景
- 動態選擇算法,或者讓算法的行為對客戶端透明。
class StrategyA {execute() {console.log("Strategy A executed");}
}class StrategyB {execute() {console.log("Strategy B executed");}
}class Context {setStrategy(strategy) {this.strategy = strategy;}executeStrategy() {this.strategy.execute();}
}const context = new Context();
context.setStrategy(new StrategyA());
context.executeStrategy(); // Strategy A executedcontext.setStrategy(new StrategyB());
context.executeStrategy(); // Strategy B executed
5、代理模式(Proxy Pattern)
特點
- 為某個對象提供代理,以控制對該對象的訪問。
- 可以用作緩存、權限控制、延遲加載等。
適用場景
- 需要在訪問對象前后執行額外的操作。
class RealSubject {request() {console.log("RealSubject: Handling request.");}
}class Proxy {constructor(realSubject) {this.realSubject = realSubject;}request() {console.log("Proxy: Logging access.");this.realSubject.request();}
}const realSubject = new RealSubject();
const proxy = new Proxy(realSubject);
proxy.request();
// Proxy: Logging access.
// RealSubject: Handling request.
6、裝飾器模式(Decorator Pattern)
特點
- 動態地給對象添加新功能,而不影響其他對象。
適用場景
- 需要擴展類的功能,而不需要創建子類。
class Coffee {cost() {return 5;}
}class MilkDecorator {constructor(coffee) {this.coffee = coffee;}cost() {return this.coffee.cost() + 2;}
}class SugarDecorator {constructor(coffee) {this.coffee = coffee;}cost() {return this.coffee.cost() + 1;}
}let coffee = new Coffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);console.log(coffee.cost()); // 8
7、MVC(Model-View-Controller)
特點
- 分離數據邏輯(Model)、用戶界面(View)和控制邏輯(Controller)。
- 適合于用戶交互密集的應用。
適用場景
- Web 應用開發(如 React 中的組件模式)。
8、MVVM(Model-View-ViewModel)
特點
- ViewModel 作為 View 和 Model 的橋梁,提供數據綁定和雙向通信。
- 在現代框架(如 Vue、Angular)中廣泛應用。
9、責任鏈模式(Chain of Responsibility)
特點
- 將請求沿著責任鏈傳遞,直到某個對象處理請求。
- 解耦請求發送者與處理者。
適用場景
- 請求的處理有多個步驟或條件,且步驟順序可能改變。
總結
- 創建型模式:如單例、工廠。
- 結構型模式:如代理、裝飾器。
- 行為型模式:如策略、責任鏈。
- 架構模式:如 MVC、MVVM。