Javascript設計模式之--單例模式

    在傳統開發工程師眼裏,單例就是保證一個類只有一個實例,實現的方法通常是先判斷實例存在與否,若是存在直接返回,若是不存在就建立了再返回,這就確保了一個類只有一個實例對象。在JavaScript裏,單例做爲一個命名空間提供者,從全局命名空間裏提供一個惟一的訪問點來訪問該對象。javascript

    在JavaScript裏,實現單例的方式有不少種,其中最簡單的一個方式是使用對象字面量的方法,其字面量裏能夠包含大量的屬性和方法: html

var mySingleton = {
    property1: "something",
    property2: "something else",
    method1: function () {
        console.log('hello world');
    }
};

    若是之後要擴展該對象,你能夠添加本身的私有成員和方法,而後使用閉包在其內部封裝這些變量和函數聲明。只暴露你想暴露的public成員和方法,樣例代碼以下:java

var mySingleton = function () {

    /* 這裏聲明私有變量和方法 */
    var privateVariable = 'something private';
    function showPrivate() {
        console.log(privateVariable);
    }

    /* 公有變量和方法(能夠訪問私有變量和方法) */
    return {
        publicMethod: function () {
            showPrivate();
        },
        publicVar: 'the public can see this!'
    };
};

var single = mySingleton();
single.publicMethod();  // 輸出 'something private'
console.log(single.publicVar); // 輸出 'the public can see this!'

    上面的代碼很不錯了,但若是咱們想作到只有在使用的時候才初始化,那該如何作呢?爲了節約資源的目的,咱們能夠另一個構造函數裏來初始化這些代碼,以下:git

var Singleton = (function () {
    var instantiated;
    function init() {
        /*這裏定義單例代碼*/
        return {
            publicMethod: function () {
                console.log('hello world');
            },
            publicProperty: 'test'
        };
    }

    return {
        getInstance: function () {
            if (!instantiated) {
                instantiated = init();
            }
            return instantiated;
        }
    };
})();

/*調用公有的方法來獲取實例:*/
Singleton.getInstance().publicMethod();

    知道了單例如何實現了,但單例用在什麼樣的場景比較好呢?其實單例通常是用在系統間各類模式的通訊協調上,下面的代碼是一個單例的最佳實踐:github

var SingletonTester = (function () {

    //參數:傳遞給單例的一個參數集合
    function Singleton(args) {

        //設置args變量爲接收的參數或者爲空(若是沒有提供的話)
        var args = args || {};
        //設置name參數
        this.name = 'SingletonTester';
        //設置pointX的值
        this.pointX = args.pointX || 6; //從接收的參數裏獲取,或者設置爲默認值
        //設置pointY的值
        this.pointY = args.pointY || 10;

    }

    //實例容器
    var instance;

    var _static = {
        name: 'SingletonTester',

        //獲取實例的方法
        //返回Singleton的實例
        getInstance: function (args) {
            if (instance === undefined) {
                instance = new Singleton(args);
            }
            return instance;
        }
    };
    return _static;
})();

var singletonTest = SingletonTester.getInstance({ pointX: 5 });
console.log(singletonTest.pointX); // 輸出 5

其它實現方式


方法1:緩存

function Universe() { // 判斷是否存在實例 if (typeof Universe.instance === 'object') { return Universe.instance; } // 其它內容 this.start_time = 0; this.bang = "Big"; // 緩存 Universe.instance = this; // 隱式返回this } // 測試 var uni = new Universe(); var uni2 = new Universe(); console.log(uni === uni2); // true

方法2:閉包

function Universe() { // 緩存的實例 var instance = this; // 其它內容 this.start_time = 0; this.bang = "Big"; // 重寫構造函數 Universe = function () { return instance; }; } // 測試 var uni = new Universe(); var uni2 = new Universe(); uni.bang = "123"; console.log(uni === uni2); // true console.log(uni2.bang); // 123

方法3:函數

function Universe() { // 緩存實例 var instance; // 從新構造函數 Universe = function Universe() { return instance; }; // 後期處理原型屬性 Universe.prototype = this; // 實例 instance = new Universe(); // 重設構造函數指針 instance.constructor = Universe; // 其它功能 instance.start_time = 0; instance.bang = "Big"; return instance; } // 測試 var uni = new Universe(); var uni2 = new Universe(); console.log(uni === uni2); // true // 添加原型屬性 Universe.prototype.nothing = true; var uni = new Universe(); Universe.prototype.everything = true; var uni2 = new Universe(); console.log(uni.nothing); // true console.log(uni2.nothing); // true console.log(uni.everything); // true console.log(uni2.everything); // true console.log(uni.constructor === Universe); // true

方式4:測試

var Universe; (function () { var instance; Universe = function Universe() { if (instance) { return instance; } instance = this; // 其它內容 this.start_time = 0; this.bang = "Big"; }; } ()); //測試代碼 var a = new Universe(); var b = new Universe(); alert(a === b); // true a.bang = "123"; alert(b.bang); // 123

參考資料

https://github.com/shichuan/javascript-patterns/blob/master/design-patterns/singleton.htmlthis

http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript

http://www.cnblogs.com/TomXu/archive/2012/02/20/2352817.html

相關文章
相關標籤/搜索