三种Swift实现单例模式的方法:全局变量,内部变量,dispatch_once方式
1. 全局变量
1
2
3
4
5
6
7
8
|
private let _singleton = Singleton()
class Singleton: NSObject {
class var sharedInstance: Singleton {
get {
return _singleton
}
}
}
|
2. 内部变量
1
2
3
4
5
6
7
8
9
10
|
class Singleton {
class var sharedInstance: Singleton {
get {
struct SingletonStruct {
static let singleton: Singleton = Singleton()
}
return SingletonStruct.singleton
}
}
}
|
3. dispatch_once方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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!
}
}
}
|
以上所述就是本文的全部内容了,希望大家能够喜欢。