swiftSingleton模式

swift在几个方面Singleton模式:

1. 全局变量

private let _singleton = Singleton()
class Singleton: NSObject {
class var sharedInstance: Singleton {
get {
return _singleton
}
}
}

2. 内部变量

class Singleton {
class var sharedInstance: Singleton {
get {
struct SingletonStruct {
static let singleton: Singleton = Singleton()
}
return SingletonStruct.singleton
}
}
}

3. dispatch_once方式

class Singleton {
class var sharedInstance: Singleton {
get {
struct SingletonStruct {
static var onceToken:dispatch_once_t = 0
static var singleton: Singleton? = nil
}
dispatch_once(&SingletonStruct.onceToken, { () -> Void in
SingletonStruct.singleton = Singleton()
})
return SingletonStruct.singleton!
}
}
}
上一篇:Vmware Workstation添加centos 7系统网络问题(无IP情况)


下一篇:java 对象与json互转