Ensure a class has only one instance, and provide a global point of access to it.html
確保某一個類只有一個實例,並且自行實例化並向整個系統提供這個實例node
NSNotificationCenter
UIApplication
NSUserDefaults
python
單例必須在程序生命週期中是惟一的git
遵循第一條規則,也就是說確保單例的惟一性,大部分狀況咱們考慮的是單例必須是thread-safe(12306搶票時,若是每一個人表明一個線程,要確保沒有兩我的買到一樣的火車票,即在多線程併發的狀況下可以保持邏輯正確,稱做線程安全)github
+ (instancetype)sharedInstance{ //我喜歡用GCD的方式 static SingleTonClass *sharedInstance = nil; //unique-ness static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ //thread-safe sharedInstance = [[SingleTonClass alloc] init]; }); return sharedInstance; }
PS:Objective-C中沒有私有方法,你仍是能夠外部調用[[SingleTonClass alloc] init];
,只能靠協議來保證swift
class SingleTonClass { //真是簡潔如swift啊, 缺點調試工具很差用,變化太快 static let sharedInstance = SingleTonClass() //thread-safe private init() {} //unique-ness }
PS: swift中全局變量static變量是由dispatch_once保證原子性的(A.K.A thread-safe)api
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Logger(object): __metaclass__ = Singleton
var singleton = function singleton(){} singleton.instance = null; singleton.getInstance = function(){ if(this.instance === null){ this.instance = new singleton(); } return this.instance; } module.exports = singleton.getInstance();