更新時間:2021-11-29 12:25:55 來源:動力節點 瀏覽1067次
JavaScript 設計模式可幫助開發人員編寫有組織、美觀且結構良好的代碼。雖然設計模式在使用時很容易被重用,但它們永遠不能補充開發人員,而只是通過提供不依賴于特定的通用解決方案來防止可能導致 Web 應用程序開發中的重大問題的小問題來支持它們問題。
這是一種特殊的方法,用于在分配內存后初始化新創建的對象。由于 JavaScript 通常是面向對象的,它最常處理對象,因此我打算深入研究對象構造函數。在 JavaScript 中可以通過三種方式創建新對象:
以下是創建構造函數設計模式的一種方法。
// This creates a new empty Object
var newObject = {};
// This creates a new empty Object
var newObject = Object.create(Object.prototype);
var newObject = newObject();
要訪問函數的屬性,您需要初始化對象。
const object = new ConstructorObject();
因此,上面的 new 關鍵字告訴 JavaScript aconstructorObject應該充當構造函數。繼承是這種設計模式不支持的一件事。在此處了解更多詳細信息。
原型模式基于原型繼承,由此創建的對象充當其他對象的原型。實際上,原型充當創建的每個對象構造函數的藍圖。
例子
var myCar= {
name:"Ford",
brake:function(){
console.log("Stop! I am applying brakes");
}
Panic : function (){
console.log ( "wait. how do you stop thuis thing?")
}
}
// use objec create to instansiate a new car
var yourCar= object.create(myCar);
//You can now see that one is a prototype of the other
console.log (yourCar.name);]
在模塊設計模式中,對原型模式進行了改進。模塊模式中設置了不同類型的修飾符(私有和公共)。您可以在沒有沖突的情況下創建類似的函數或屬性。公開重命名函數具有靈活性。令人生畏的部分是無法從外部環境覆蓋創建的函數。
例子
function AnimalContainter () {
const container = [];
function addAnimal (name) {
container.push(name);
}
function getAllAnimals() {
return container;
}
function removeAnimal(name) {
const index = container.indexOf(name);
if(index < 1) {
throw new Error('Animal not found in container');
}
container.splice(index, 1)
}
return {
add: addAnimal,
get: getAllAnimals,
remove: removeAnimal
}
}
const container = AnimalContainter();
container.add('Hen');
container.add('Goat');
container.add('Sheep');
console.log(container.get()) //Array(3) ["Hen", "Goat", "Sheep"]
container.remove('Sheep')
console.log(container.get()); //Array(2) ["Hen", "Goat"]
在只需要創建一個實例的場景中是必不可少的,例如一個數據庫連接。只能在連接關閉時創建實例,或者確保在打開新實例之前關閉打開的實例。這種模式也被稱為嚴格模式,與這種模式相關的一個缺點是它在測試中的艱巨體驗,因為它隱藏的依賴對象不容易被挑出來進行測試。
例子
function DatabaseConnection () {
let databaseInstance = null;
// tracks the number of instances created at a certain time
let count = 0;
function init() {
console.log(`Opening database #${count + 1}`);
//now perform operation
}
function createIntance() {
if(databaseInstance == null) {
databaseInstance = init();
}
return databaseInstance;
}
function closeIntance() {
console.log('closing database');
databaseInstance = null;
}
return {
open: createIntance,
close: closeIntance
}
}
const database = DatabseConnection();
database.open(); //Open database #1
database.open(); //Open database #1
database.open(); //Open database #1
database.close(); //close database
它是一種創建對象,無需構造函數即可創建對象。它提供了創建對象的通用接口,我們可以在其中指定要創建的工廠對象的類型。因此,我們只指定對象,工廠實例化并返回給我們使用。當對象組件設置具有高度復雜性并且當我們想要根據所處環境輕松創建對象的不同實例時,使用工廠模式是明智的。當處理許多對象時,我們也可以使用工廠模式共享相同屬性的小對象以及在組合需要解耦的對象時。
例子
// Dealer A
DealerA = {};
DealerA.title = function title() {
return "Dealer A";
};
DealerA.pay = function pay(amount) {
console.log(
`set up configuration using username: ${this.username} and password: ${
this.password
}`
);
return `Payment for service ${amount} is successful using ${this.title()}`;
};
//Dealer B
DealerB = {};
DealerB.title = function title() {
return "Dealer B";
};
DealerB.pay = function pay(amount) {
console.log(
`set up configuration using username: ${this.username}
and password: ${this.password}`
);
return `Payment for service ${amount} is successful using ${this.title()}`;
};
//@param {*} DealerOption
//@param {*} config
function DealerFactory(DealerOption, config = {}) {
const dealer = Object.create(dealerOption);
Object.assign(dealer, config);
return dealer;
}
const dealerFactory = DealerFactory(DealerA, {
username: "user",
password: "pass"
});
console.log(dealerFactory.title());
console.log(dealerFactory.pay(12));
const dealerFactory2 = DealerFactory(DealerB, {
username: "user2",
password: "pass2"
});
console.log(dealerFactory2.title());
console.log(dealerFactory2.pay(50));
觀察者設計模式在對象與其他對象集同時通信的地方很方便。在這種觀察者模式中,沒有不必要的跨狀態推拉事件,而是涉及的模塊只修改數據的當前狀態。
例子
function Observer() {
this.observerContainer = [];
}
Observer.prototype.subscribe = function (element) {
this.observerContainer.push(element);
}
// the following removes an element from the container
Observer.prototype.unsubscribe = function (element) {
const elementIndex = this.observerContainer.indexOf(element);
if (elementIndex > -1) {
this.observerContainer.splice(elementIndex, 1);
}
}
/**
* we notify elements added to the container by calling
* each subscribed components added to our container
*/
Observer.prototype.notifyAll = function (element) {
this.observerContainer.forEach(function (observerElement) {
observerElement(element);
});
}
最后,我想說命令設計模式結束了我對 JavaScript 設計模式的 7 個最佳總結。命令設計模式將方法調用、操作或請求封裝到單個對象中,以便我們可以自行決定傳遞方法調用。命令設計模式讓我們有機會從任何執行命令的對象發出命令,并將責任委托給不同的對象。這些命令以run()和execute()格式顯示。
(function(){
var carManager = {
//information requested
requestInfo: function( model, id ){
return "The information for " + model + " with ID " + id + " is foo bar";
},
// now purchase the car
buyVehicle: function( model, id ){
return "You have successfully purchased Item " + id + ", a " + model;
},
// now arrange a viewing
arrangeViewing: function( model, id ){
return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
}
};
})();
使用設計模式對 JavaScript 開發人員是有益的。使用設計模式的一些主要優點包括項目的可維護性以及減少開發周期中不必要的工作。盡管 JavaScript 設計模式可以為復雜問題提供解決方案,更不用說快速開發和生產力,但斷定這些設計模式可以取代開發人員是不恰當的。如果大家想了解更多相關知識,可以關注一下動力節點的Java視頻,里面的內容豐富,通俗易懂,適合小白學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習