常见的有这么4种方法
第一种简单到爆的
final class Single: NSObject {
static let shared = Single()
private override init() {}
}
final关键字的作用是这个类或方法不希望被继承和重写
第二种
public extension DispatchQueue {
private static var onceToken = [String]()
public class func once(_ token: String, _ block:@escaping () -> Void) {
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
if onceToken.contains(token) {
return
}
onceToken.append(token)
block()
}
}
final class Single2: NSObject {
static func shared() -> Single2 {
struct Singleton {
static var single = Single2()
}
DispatchQueue.once("YouShaoduo") {
Singleton.single = shared()
}
return Singleton.single
}
private override init() {}
}
完全是OC风格的单例,但是由于Swift3中废弃了原来的dispatch_once_t,所以需要先给DispatchQueue添加一个extension,实现原先的**dispatch_once_t效果
第三种
private let single = Single3()
final class Single3: NSObject {
static var shared: Single3 {
return single
}
fileprivate override init() {}
}
第四种
final class Single4: NSObject {
static var shared: Single4 {
struct Static {
static let instance: Single4 = Single4()
}
return Static.instance
}
private override init() {}
}
在方法内定义静态变量
网友评论