美文网首页
Swift严格的单例写法

Swift严格的单例写法

作者: 囧书 | 来源:发表于2017-02-17 17:39 被阅读166次

相比OC,Swift有很优雅的实现单例的写法。

实现

单例类Tools

class Tools {
    // 单例
    static let shared = Tools()

    // 私有化构造方法,不允许外界创建实例
    private init() {
        // 进行初始化工作
    }
}

客户端调用:

let tools = Tools.shared

说明

  1. 当尝试使用
let tools = Tools()

这种方法去创建一个Tools实例时,编译器将会报错,因为我们把init()方法私有化了,类外无法通过构造方法创建新实例。

  1. static let shared = Tools()是线程安全的,并且将在第一次调用时进行赋值。这在苹果的官方博客已有说明:

“The lazy initializer for a global variable (also for static members of structs and enums) is run the first time that global is accessed, and is launched as dispatch_once to make sure that the initialization is atomic. This enables a cool way to use dispatch_once in your code: just declare a global variable with an initializer and mark it private.”
“全局变量(还有结构体和枚举体的静态成员)的Lazy初始化方法会在其被访问的时候调用一次。类似于调用dispatch_once以保证其初始化的原子性。这样就有了一种很酷的单次调用方式:只声明一个全局变量和私有的初始化方法即可。”

就这么愉快地写好了单例。

相关文章

网友评论

      本文标题:Swift严格的单例写法

      本文链接:https://www.haomeiwen.com/subject/ynelwttx.html