javascript 模式(2)——單例模式

來源:互聯網
上載者:User

標籤:

單聊模式是一種非常極端的模式,它保證了一個類在整個應用程式定義域中只有一個實體,意味著當你多次建立某一個類的執行個體的時候它們都是第一次建立的那個。

在Java或c#環境實現單例模式很簡單,只需要定義靜態變數即可,將對象存入靜態變數中即可,靜態變數不會隨類執行個體而變換。同理在javascript也是類似實現原理。

 

公用靜態變數實現單例模式
var Earth = (function () {    if (typeof Earth.instance === ‘object‘) {        return Earth.instance;    }    this.name = "地球";    this.age = 46 * 1000 * 1000 * 10000;    Earth.instance = this;    return Earth.instance;});

代碼中的Earth.instance 即為公用靜態變數,在執行個體化的對象earth1中是看不見公用靜態變數

但在Earth類中是可以看見的

var earth1 = new Earth();var earth2 = new Earth();console.log(earth1 === earth2);

由於是單例模式因此結果顯然為‘true’

 

私人靜態變數實現單例模式

將執行個體儲存至公有變數中很簡單,但有一個致命問題公開變數可以在外部被更改,因此最好的方式還是使用私人靜態變數,使用私人靜態變數需要通過及時函數和閉包來實現。

var Earth = (function () {      var instance;    return function () {            if (typeof instance === ‘object‘) {            return instance;        }        this.name = "地球";        this.age = 46 * 1000 * 1000 * 10000;        instance = this;        return instance;    }}());

整個函數返回一個閉包函數,並且立即執行,及時函數表達方式:(function(){}())

再次執行

var earth1 = new Earth();var earth2 = new Earth();console.log(earth1 === earth2);

得到結果依然為’true’

總結:

單例模式是非常極端模式,可通過靜態變數儲存執行個體的方式來實現,通過私人靜態實現需要依靠於及時函數和閉包,關於及時函數和閉包就不再這裡累贅了。

javascript 模式(2)——單例模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.