單例模式

【風(fēng)趣的解釋】

Singleton Mode

最近桃花運不錯,QQ上加了一個漂亮美眉,微信上加了兩個漂亮美眉。加個美眉,聊聊天,反正又不花錢!她們現(xiàn)在都認識我了,只要她們想到那個又高又帥,姓周的小子,那就指的是我。我真是沒救了,整天做白日夢...

【正式的解釋】

單例模式

一種特殊的類,只有一個實例。通過單例模式可以保證系統(tǒng)中一個類只有一個實例而且該實例易于外界訪問,從而方便對實例個數(shù)的控制并節(jié)約系統(tǒng)資源。

【Python版】

#-*- coding:utf-8 -*-

#這就是我,世界上獨一無二
class Me(object):
    __instance = None

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super(cls.__class__, cls).__new__(
                                 cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        self.__name = "Mr.Zhou"
        self.__height = "120cm"
        self.__gender = "man"

    def getName(self):
        return self.__name

    def getHeight(self):
        return self.__height

    def getGender(self):
        return self.__gender

    def getIntroduction(self):
        return "Hi, I am " + self.__name + ", " + self.__height + ", and a " + self.__gender + "."

if __name__ == "__main__":
    m1 = Me()
    m2 = Me()

    print m1 == m2
    print m1.getIntroduction()

"""print out

True
Hi, I am Mr.Zhou, 120cm, and a man.
"""

【JS版】

//這就是我,世界上獨一無二
function Me(){
    if(typeof Me.instance === "object"){
        return Me.instance;
    }

    this.__name = 'Mr.Zhou',
    this.__height = '120cm',
    this.__gender = 'man';

    Me.instance = this;
}

Me.prototype = {
    getName: function(){
        return this.__name;
    },
    getHeight: function(){
        return this.__height;
    },
    getGender: function(){
        return this.__gender;
    },
    getIntroduction: function(){
        return 'Hi, I am ' + this.__name + ', ' + this.__height + ', and a ' + this.__gender + '.';
    }
};


var m1 = new Me();
var m2 = new Me();

console.log(m1===m2);
console.log(m1.getIntroduction());

/*console out

true
Hi, I am Mr.Zhou, 120cm, and a man.
*/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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