程序员

单例模式

2013-08-13  本文已影响646人  周文洪

【风趣的解释】

Singleton Mode

最近桃花运不错,QQ上加了一个漂亮美眉,微信上加了两个漂亮美眉。加个美眉,聊聊天,反正又不花钱!她们现在都认识我了,只要她们想到那个又高又帅,姓周的小子,那就指的是我。我真是没救了,整天做白日梦...

【正式的解释】

单例模式

一种特殊的类,只有一个实例。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。

【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.
*/
上一篇 下一篇

猜你喜欢

热点阅读