【風趣的解釋】
Singleton Mode
最近桃花運不錯,QQ上加了一個漂亮美眉,微信上加了兩個漂亮美眉。加個美眉,聊聊天,反正又不花錢!她們現在都認識我了,只要她們想到那個又高又帥,姓周的小子,那就指的是我。我真是沒救了,整天做白日夢...
【正式的解釋】
單例模式
一種特殊的類,只有一個實例。通過單例模式可以保證系統(tǒng)中一個類只有一個實例而且該實例易于外界訪問,從而方便對實例個數的控制并節(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.
*/