新聞中心
設(shè)計(jì)模式是解決軟件設(shè)計(jì)中常見問題的通用模板,它們可以幫助開發(fā)人員編寫可重用、可維護(hù)和可理解的代碼,在 JavaScript 中,有許多不同的設(shè)計(jì)模式,如工廠模式、單例模式、觀察者模式等。

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁(yè)設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、微信小程序、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了蒲縣免費(fèi)建站歡迎大家使用!
1、工廠模式
工廠模式是一種創(chuàng)建型設(shè)計(jì)模式,它提供了一種創(chuàng)建對(duì)象的最佳方式,在工廠模式中,我們?cè)趧?chuàng)建對(duì)象時(shí)不會(huì)對(duì)客戶端暴露創(chuàng)建邏輯,而是使用一個(gè)共同的接口來指向新創(chuàng)建的對(duì)象。
class Car {
constructor(options) {
this.doors = options.doors || 4;
this.state = options.state || "brand new";
this.color = options.color || "silver";
}
}
class Truck {
constructor(options) {
this.state = options.state || "used";
this.wheelSize = options.wheelSize || "large";
this.color = options.color || "blue";
}
}
class VehicleFactory {
createVehicle(options) {
switch (options.vehicleType) {
case 'car':
return new Car(options);
case 'truck':
return new Truck(options);
// ...
}
}
}
2、單例模式
單例模式是一種創(chuàng)建型設(shè)計(jì)模式,它保證一個(gè)類只有一個(gè)實(shí)例,并提供一個(gè)全局訪問點(diǎn),這在需要頻繁創(chuàng)建和銷毀的對(duì)象時(shí)非常有用。
let Singleton = (function () {
let instance;
function createInstance() {
let object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
let instance1 = Singleton.getInstance();
let instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true
3、觀察者模式
觀察者模式是一種行為設(shè)計(jì)模式,它定義了對(duì)象之間的一對(duì)多依賴關(guān)系,當(dāng)一個(gè)對(duì)象改變狀態(tài)時(shí),它的所有依賴者都會(huì)收到通知并自動(dòng)更新。
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
}
unsubscribe(observer) {
this.observers = this.observers.filter((obs) => observer !== obs);
}
fire(action) {
this.observers.forEach((observer) => {
observer.update(action);
});
}
}
class Observer {
constructor(state) {
this.state = state;
this.initialState = state;
}
update(action) {
switch (action.type) {
case 'INCREMENT':
this.state = ++this.state;
break;
case 'DECREMENT':
this.state = this.state;
break;
default:
this.state = this.initialState;
}
}
}
分享題目:JavaScript設(shè)計(jì)模式:深入了解有效的設(shè)計(jì)
網(wǎng)站網(wǎng)址:http://www.dlmjj.cn/article/djhjshc.html


咨詢
建站咨詢
