設(shè)計(jì)模式的單例模式

1. 什么是單例模式?

單例模式定義:一個(gè)類只能有一個(gè)實(shí)例,即使多次實(shí)例化該類,也只返回第一次實(shí)例化后的實(shí)例對(duì)象。單例模式能減少不必要的內(nèi)存開銷, 并且減少全局函數(shù)和變量沖突。

2. 代碼實(shí)現(xiàn)

以下實(shí)現(xiàn)的單例模式均為“惰性單例”:惰性單例指的是在需要的時(shí)候才創(chuàng)建對(duì)象實(shí)例。惰性單例在實(shí)際開發(fā)中非常有用,是單例模式的重點(diǎn)。instance實(shí)例對(duì)象總是在我們調(diào)用Singleton.getInstance的時(shí)候才被創(chuàng)建,而不是在頁(yè)面加載好的時(shí)候就創(chuàng)建。

javascript 實(shí)現(xiàn)

function Singleton(name){
  this.name = name;
  this.instance = null;
}

Singleton.prototype.getName = function(){
  console.log(this.name);
};

Singleton.getInstance = function(name){
  if(! this.instance){
      this.instance  = new Singleton(name);
  }
  return this.instance;
};

var a = Singleton.getInstance('a');
var b = Singleton.getInstance('b');
console.log(a === b);//true
console.log(a.getName(), b.getName());//a a

ES6 實(shí)現(xiàn)

class Singleton {
    constructor(name) {
        this.name = name;
    }
    static getInstance(name) {
     // ES6中可以使用static方法代替閉包存儲(chǔ)單例
        if(!Singleton.instance) {
            Singleton.instance = new Singleton(name)
        }
        return Singleton.instance;
    }
    getName() {
        return this.name;
    }
}
const a = Singleton.getInstance('a');
const b = Singleton.getInstance('b');
console.log(a === b);//true
console.log(a.getName() === b.getName());//true
console.log(a.getName(), b.getName());//a a
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容