JS中的單例模式及單例模式原型類的實(shí)現(xiàn)

class div {constructor() {return document.createElement("div");}}btn.addEventListener("click", function (event) {const div = new Div();document.body.appendChild(div);});
現(xiàn)在頁面上的這個(gè)按鈕每被點(diǎn)擊一下就會(huì)生成一個(gè)div,但是現(xiàn)在如果這個(gè)div是登錄框,我當(dāng)然就會(huì)想要這段函數(shù)只生成一個(gè),這時(shí)候就可以用到單例模式的思想:讓一個(gè)類只會(huì)生成一個(gè)實(shí)例。
在js里實(shí)現(xiàn)單例模式很簡單,只要使用閉包就能做到,這是使用ES6的class語法實(shí)現(xiàn)的單例模式:
let div = null;class Div {constructor() {return div ?? (div = document.createElement("div"));}}
這樣,通過閉包實(shí)現(xiàn)了單例模式,無論點(diǎn)擊多少次按鈕,只會(huì)生成一個(gè)div。
考慮到單例模式應(yīng)用的廣泛,我實(shí)現(xiàn)了一個(gè)原型類,通過繼承該原型類可以直接得到一個(gè)單例模式的類:
const SingletonConstructor = (function () {const instances = {};return class {constructor(Constructor) {let className = new.target.name;if (instances[className]) {return instances[className];} else {let instance = new Constructor();Object.setPrototypeOf.call(null, instance, new.target.prototype);return (instances[className] = instance);}}};})();class Div extends SingletonConstructor {constructor() {super(function () {return document.createElement("div");});}}
需要設(shè)計(jì)為單例的類只需要繼承這個(gè)原型類后在構(gòu)造函數(shù)的super中寫入構(gòu)造函數(shù)就能實(shí)現(xiàn)單例模式。
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊中國公眾號(hào)
![]()

評(píng)論
圖片
表情
