JavaScript 結(jié)構(gòu)型設(shè)計模式使用場景分析
1. 代理模式
1.1. 使用場景
代理模式在不改變原始對象的前提下,通過代理對象控制對其訪問,通常用于權(quán)限控制、延遲加載、遠程調(diào)用等場景。在前端開發(fā)中,可以通過代理模式對網(wǎng)絡(luò)請求、緩存機制等進行控制。
1.2. 代碼實現(xiàn)
class ApiService {
request() {
console.log('Making API request...');
return 'Response from API';
}
}
class ApiServiceProxy {
constructor() {
this.apiservice = new ApiService();
this.cache = null;
}
request() {
if (!this.cache) {
console.log('Fetching from API...');
this.cache = this.apiservice.request();
} else {
console.log('Returning cached response...');
}
return this.cache;
}
}
// 使用代理模式
const apiProxy = new ApiServiceProxy();
console.log(apiProxy.request()); // Fetching from API... Response from API
console.log(apiProxy.request()); // Returning cached response... Response from API1.3. 詳細注釋
- ApiService:表示原始對象,提供基礎(chǔ)的 API 請求功能。
- ApiServiceProxy:代理類,控制對 ApiService 的訪問,緩存請求結(jié)果以避免多次 API 調(diào)用。
- 代理模式用于在不修改原始對象的情況下,添加緩存或權(quán)限控制等功能。
1.4. 實際應(yīng)用
- 代理模式常用于緩存、權(quán)限管理、遠程代理等場景,如在前端緩存 API 請求、延遲加載圖片等。
2. 適配器模式
2.1. 使用場景
適配器模式用于將不兼容的接口轉(zhuǎn)換為兼容的接口,解決不同對象或模塊之間的兼容性問題。在前端開發(fā)中,適配器模式可用于將第三方庫的接口適配為項目內(nèi)部通用的接口形式。
2.2. 代碼實現(xiàn)
class OldApi {
oldRequest() {
return 'Old API response';
}
}
class Adapter {
constructor(oldApi) {
this.oldApi = oldApi;
}
newRequest() {
return this.oldApi.oldRequest();
}
}
// 使用適配器模式
const oldApi = new OldApi();
const adapter = new Adapter(oldApi);
console.log(adapter.newRequest()); // Old API response2.3. 詳細注釋
- OldApi:表示舊的接口,提供老舊的請求方式。
- Adapter:適配器,將舊接口適配為新的接口,使得可以在新環(huán)境中使用舊的功能。
- 適配器模式解決了接口不兼容的問題,便于老舊代碼與新代碼的集成。
2.4. 實際應(yīng)用
- 適配器模式常用于集成不同版本的接口或庫,如將舊版 API 接口適配到新版項目中。
3. 裝飾器模式
3.1. 使用場景
裝飾器模式用于在不修改現(xiàn)有對象的情況下,動態(tài)地為其添加功能。在前端中,裝飾器模式常用于為對象或函數(shù)動態(tài)添加功能,如事件處理、日志記錄等。
3.2. 代碼實現(xiàn)
class Coffee {
cost() {
return 5;
}
}
class MilkDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost() + 1;
}
}
class SugarDecorator {
constructor(coffee) {
this.coffee = coffee;
}
cost() {
return this.coffee.cost() + 0.5;
}
}
// 使用裝飾器模式
let coffee = new Coffee();
coffee = new MilkDecorator(coffee);
coffee = new SugarDecorator(coffee);
console.log(coffee.cost()); // 6.53.3. 詳細注釋
- Coffee:原始對象,表示基礎(chǔ)的咖啡,提供基本功能。
- MilkDecorator 和 SugarDecorator:裝飾器類,動態(tài)為 Coffee 對象添加牛奶和糖的功能。
- 裝飾器模式通過包裝對象的方式,動態(tài)添加功能而不修改原始類。
3.3. 實際應(yīng)用
- 裝飾器模式常用于前端中動態(tài)功能的添加,如為按鈕添加事件處理、為組件增加樣式等。
4. 橋接模式
4.1. 使用場景
橋接模式用于將抽象部分和實現(xiàn)部分分離,使它們可以獨立變化。常用于當一個對象有多個維度的變化時,將這些變化解耦。在前端開發(fā)中,橋接模式用于將功能和 UI 的實現(xiàn)分離,使得它們可以獨立演進。
4.2. 代碼實現(xiàn)
class Shape {
constructor(color) {
this.color = color;
}
draw() {
throw new Error('draw() must be implemented');
}
}
class Circle extends Shape {
draw() {
console.log(`Drawing a ${this.color.getColor()} circle`);
}
}
class Color {
getColor() {
throw new Error('getColor() must be implemented');
}
}
class RedColor extends Color {
getColor() {
return 'red';
}
}
class BlueColor extends Color {
getColor() {
return 'blue';
}
}
// 使用橋接模式
const red = new RedColor();
const blue = new BlueColor();
const redCircle = new Circle(red);
redCircle.draw(); // Drawing a red circle
const blueCircle = new Circle(blue);
blueCircle.draw(); // Drawing a blue circle4.3. 詳細注釋
- Shape:抽象類,定義了 draw 方法。
- Circle:具體實現(xiàn)類,實現(xiàn)了 Shape 的 draw 方法。
- Color:表示顏色抽象,可以有不同的顏色實現(xiàn)類如 RedColor 和 BlueColor。
- 橋接模式將形狀和顏色的實現(xiàn)解耦,可以獨立擴展。
4.4. 實際應(yīng)用
- 橋接模式常用于將功能和實現(xiàn)分離,如在圖形繪制中分離形狀和顏色、在 UI 組件中分離外觀和行為。
5. 組合模式
5.1. 使用場景
組合模式用于將對象組合成樹形結(jié)構(gòu),以表示“部分-整體”的層次結(jié)構(gòu)。前端中,組合模式常用于構(gòu)建層次結(jié)構(gòu)的 UI 組件,如菜單、文件夾結(jié)構(gòu)等。
5.2. 代碼實現(xiàn)
class MenuItem {
constructor(name) {
this.name = name;
}
show() {
console.log(this.name);
}
}
class Menu {
constructor(name) {
this.name = name;
this.items = [];
}
add(item) {
this.items.push(item);
}
show() {
console.log(this.name);
this.items.forEach(item => item.show());
}
}
// 使用組合模式
const fileMenu = new Menu('File');
fileMenu.add(new MenuItem('New'));
fileMenu.add(new MenuItem('Open'));
const editMenu = new Menu('Edit');
editMenu.add(new MenuItem('Undo'));
editMenu.add(new MenuItem('Redo'));
const mainMenu = new Menu('Main Menu');
mainMenu.add(fileMenu);
mainMenu.add(editMenu);
mainMenu.show();5.3. 詳細注釋
- MenuItem:表示基礎(chǔ)菜單項,提供 show 方法。
- Menu:組合類,包含多個 MenuItem 或其他 Menu,提供組合的 show 方法。
- 組合模式允許樹形結(jié)構(gòu)的對象組合和處理,實現(xiàn)部分與整體的遞歸處理。
5.4. 實際應(yīng)用
- 組合模式常用于前端的樹形結(jié)構(gòu)、層次化菜單、文件目錄管理等場景。
6. 外觀模式
6.1. 使用場景
外觀模式提供了一個簡化的接口來訪問復(fù)雜的系統(tǒng),隱藏內(nèi)部實現(xiàn)細節(jié),減少客戶端的復(fù)雜性。在前端開發(fā)中,外觀模式常用于為復(fù)雜的庫或系統(tǒng)提供簡化的 API。
6.2. 代碼實現(xiàn)
class Subsystem1 {
operation() {
return 'Subsystem1 operation';
}
}
class Subsystem2 {
operation() {
return 'Subsystem2 operation';
}
}
class Facade {
constructor() {
this.subsystem1 = new Subsystem1();
this.subsystem2 = new Subsystem2();
}
operation() {
return `${this.subsystem1.operation()} + ${this.subsystem2.operation()}`;
}
}
// 使用外觀模式
const facade = new Facade();
console.log(facade.operation()); // Subsystem1 operation + Subsystem2 operation6.3. 詳細注釋
- Subsystem1 和 Subsystem2:表示復(fù)雜系統(tǒng)的部分。
- Facade:外觀類,提供簡化的 operation 方法,統(tǒng)一調(diào)用多個子系統(tǒng)。
- 外觀模式通過提供一個簡化的接口,隱藏了復(fù)雜系統(tǒng)的細節(jié)。
6.4. 實際應(yīng)用
- 外觀模式常用于封裝復(fù)雜的子系統(tǒng),如封裝多種 API 調(diào)用、封裝復(fù)雜的 UI 邏輯等。
7. 享元模式
7.1. 使用場景
享元模式通過共享相同的對象來減少內(nèi)存消耗,適用于需要大量相似對象的場景。在前端開發(fā)中,享元模式用于優(yōu)化性能,如緩存對象、共享數(shù)據(jù)等。
7.2. 代碼實現(xiàn)
class Flyweight {
constructor(sharedState) {
this.sharedState = sharedState;
}
operation(uniqueState) {
console.log(`Shared: ${this.sharedState}, Unique: ${uniqueState}`);
}
}
class FlyweightFactory {
constructor() {
this.flyweights = {};
}
getFlyweight(sharedState) {
if (!this.flyweights[sharedState]) {
this.flyweights[sharedState] = new Flyweight(sharedState);
}
return this.flyweights[sharedState];
}
}
// 使用享元模式
const factory = new FlyweightFactory();
const flyweight1 = factory.getFlyweight('Shared1');
flyweight1.operation('Unique1');
const flyweight2 = factory.getFlyweight('Shared1');
flyweight2.operation('Unique2');
console.log(flyweight1 === flyweight2); // true7.3. 詳細注釋
- Flyweight:享元對象,包含共享的狀態(tài) sharedState 。
- FlyweightFactory:負責創(chuàng)建和管理共享的享元對象,避免重復(fù)創(chuàng)建相同的對象。
- 享元模式通過共享對象,減少了內(nèi)存消耗,提升了系統(tǒng)性能。
7.4. 實際應(yīng)用
享元模式常用于緩存機制、對象池、共享數(shù)據(jù)等需要大量相似對象的場景。
到此這篇關(guān)于JavaScript 結(jié)構(gòu)型設(shè)計模式詳解的文章就介紹到這了,更多相關(guān)js結(jié)構(gòu)型設(shè)計模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
BootStrap響應(yīng)式導(dǎo)航條實例介紹
響應(yīng)式導(dǎo)航條就是可以在不同的設(shè)備下查看不同的效果。這篇文章主要介紹了BootStrap響應(yīng)式導(dǎo)航條實例介紹的相關(guān)資料,小編認為本文介紹的非常的不錯,特此分享給大家,供大家參考2016-05-05
JS中new?Blob()詳解及blob轉(zhuǎn)file示例
這篇文章主要給大家介紹了關(guān)于JS中new?Blob()詳解及blob轉(zhuǎn)file的相關(guān)資料,Blob?Blob(Binary?Large?Object)表示二進制類型的大對象,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-11-11
利用JavaScript創(chuàng)建一個兔年春節(jié)倒數(shù)計時器
這篇文章主要介紹了如何利用JavaScript創(chuàng)建一個兔年春節(jié)倒數(shù)計時器,文中的示例代碼講解詳細,對我們學習JavaScript有一定的幫助,需要的可以參考一下2023-01-01

