更新時(shí)間:2021-11-29 12:25:55 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1380次
JavaScript 設(shè)計(jì)模式可幫助開(kāi)發(fā)人員編寫有組織、美觀且結(jié)構(gòu)良好的代碼。雖然設(shè)計(jì)模式在使用時(shí)很容易被重用,但它們永遠(yuǎn)不能補(bǔ)充開(kāi)發(fā)人員,而只是通過(guò)提供不依賴于特定的通用解決方案來(lái)防止可能導(dǎo)致 Web 應(yīng)用程序開(kāi)發(fā)中的重大問(wèn)題的小問(wèn)題來(lái)支持它們問(wèn)題。
這是一種特殊的方法,用于在分配內(nèi)存后初始化新創(chuàng)建的對(duì)象。由于 JavaScript 通常是面向?qū)ο蟮?,它最常處理?duì)象,因此我打算深入研究對(duì)象構(gòu)造函數(shù)。在 JavaScript 中可以通過(guò)三種方式創(chuàng)建新對(duì)象:
以下是創(chuàng)建構(gòu)造函數(shù)設(shè)計(jì)模式的一種方法。
// This creates a new empty Object
var newObject = {};
// This creates a new empty Object
var newObject = Object.create(Object.prototype);
var newObject = newObject();
要訪問(wèn)函數(shù)的屬性,您需要初始化對(duì)象。
const object = new ConstructorObject();
因此,上面的 new 關(guān)鍵字告訴 JavaScript aconstructorObject應(yīng)該充當(dāng)構(gòu)造函數(shù)。繼承是這種設(shè)計(jì)模式不支持的一件事。在此處了解更多詳細(xì)信息。
原型模式基于原型繼承,由此創(chuàng)建的對(duì)象充當(dāng)其他對(duì)象的原型。實(shí)際上,原型充當(dāng)創(chuàng)建的每個(gè)對(duì)象構(gòu)造函數(shù)的藍(lán)圖。
例子
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);]
在模塊設(shè)計(jì)模式中,對(duì)原型模式進(jìn)行了改進(jìn)。模塊模式中設(shè)置了不同類型的修飾符(私有和公共)。您可以在沒(méi)有沖突的情況下創(chuàng)建類似的函數(shù)或?qū)傩?。公開(kāi)重命名函數(shù)具有靈活性。令人生畏的部分是無(wú)法從外部環(huán)境覆蓋創(chuàng)建的函數(shù)。
例子
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"]
在只需要?jiǎng)?chuàng)建一個(gè)實(shí)例的場(chǎng)景中是必不可少的,例如一個(gè)數(shù)據(jù)庫(kù)連接。只能在連接關(guān)閉時(shí)創(chuàng)建實(shí)例,或者確保在打開(kāi)新實(shí)例之前關(guān)閉打開(kāi)的實(shí)例。這種模式也被稱為嚴(yán)格模式,與這種模式相關(guān)的一個(gè)缺點(diǎn)是它在測(cè)試中的艱巨體驗(yàn),因?yàn)樗[藏的依賴對(duì)象不容易被挑出來(lái)進(jìn)行測(cè)試。
例子
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
它是一種創(chuàng)建對(duì)象,無(wú)需構(gòu)造函數(shù)即可創(chuàng)建對(duì)象。它提供了創(chuàng)建對(duì)象的通用接口,我們可以在其中指定要?jiǎng)?chuàng)建的工廠對(duì)象的類型。因此,我們只指定對(duì)象,工廠實(shí)例化并返回給我們使用。當(dāng)對(duì)象組件設(shè)置具有高度復(fù)雜性并且當(dāng)我們想要根據(jù)所處環(huán)境輕松創(chuàng)建對(duì)象的不同實(shí)例時(shí),使用工廠模式是明智的。當(dāng)處理許多對(duì)象時(shí),我們也可以使用工廠模式共享相同屬性的小對(duì)象以及在組合需要解耦的對(duì)象時(shí)。
例子
// 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));
觀察者設(shè)計(jì)模式在對(duì)象與其他對(duì)象集同時(shí)通信的地方很方便。在這種觀察者模式中,沒(méi)有不必要的跨狀態(tài)推拉事件,而是涉及的模塊只修改數(shù)據(jù)的當(dāng)前狀態(tài)。
例子
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);
});
}
最后,我想說(shuō)命令設(shè)計(jì)模式結(jié)束了我對(duì) JavaScript 設(shè)計(jì)模式的 7 個(gè)最佳總結(jié)。命令設(shè)計(jì)模式將方法調(diào)用、操作或請(qǐng)求封裝到單個(gè)對(duì)象中,以便我們可以自行決定傳遞方法調(diào)用。命令設(shè)計(jì)模式讓我們有機(jī)會(huì)從任何執(zhí)行命令的對(duì)象發(fā)出命令,并將責(zé)任委托給不同的對(duì)象。這些命令以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 + " ) ";
}
};
})();
使用設(shè)計(jì)模式對(duì) JavaScript 開(kāi)發(fā)人員是有益的。使用設(shè)計(jì)模式的一些主要優(yōu)點(diǎn)包括項(xiàng)目的可維護(hù)性以及減少開(kāi)發(fā)周期中不必要的工作。盡管 JavaScript 設(shè)計(jì)模式可以為復(fù)雜問(wèn)題提供解決方案,更不用說(shuō)快速開(kāi)發(fā)和生產(chǎn)力,但斷定這些設(shè)計(jì)模式可以取代開(kāi)發(fā)人員是不恰當(dāng)?shù)摹H绻蠹蚁肓私飧嘞嚓P(guān)知識(shí),可以關(guān)注一下動(dòng)力節(jié)點(diǎn)的Java視頻,里面的內(nèi)容豐富,通俗易懂,適合小白學(xué)習(xí),希望對(duì)大家能夠有所幫助。
Java實(shí)驗(yàn)班
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
Java就業(yè)班
有基礎(chǔ) 直達(dá)就業(yè)
Java夜校直播班
業(yè)余時(shí)間 高薪轉(zhuǎn)行
Java在職加薪班
工作1~3年,加薪神器
Java架構(gòu)師班
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話與您溝通安排學(xué)習(xí)