美文网首页
[iOS Swift] Singleton——单例模式的使用与理

[iOS Swift] Singleton——单例模式的使用与理

作者: ThomasRobot | 来源:发表于2016-11-28 10:37 被阅读119次

    单例模式属于创建型的设计模式。它提供了一种创建对象的最佳方式。

    示例代码:

    class MyClass {
        static let shared = MyClass()
    
        private init() {
            // Private initialization to ensure just one instance is created.
        }
    }
    

    使用方式:

    let instance = MyClass.shared
    
    // iOS 开发中常用的单例
    UIApplication.shared
    NSNotification.shared
    NSUserDefaults.shared
    

    理解

    Swift的单行单例要怎么理解?从The Swift Programming Language(中文版)Apple Swift Blog中可以找到答案。

    Swift的语法中说明,使用关键字 static 来定义类型属性。

    存储型类型属性是延迟初始化的,它们只有在第一次被访问的时候才会被初始化。即使它们被多个线程同时访问,系统也保证只会对其进行一次初始化,并且不需要对其使用 lazy 修饰符。—— From The Swift Programming Language(中文版)

    因此,使用static修饰的类型属性,其自带隐性的lazy修饰,且明确说明了即使它们被多个线程同时访问,系统也只进行一次初始化。

    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. —— From Apple Swift Blog

    这是Apple针对早期Swift版本的博客说明,这也说明了类型属性的懒加载模式和初始化的原子性。而初始化的原子性又是单例模式必须遵从的原则。

    除此以外,单例模式还需遵从「构造函数必须是私有的」的这一原则,目的是为了防止使用构造函数重复初始化多个实例。因此,少了private的构造函数是不完整的单例模式!

    参考

    相关文章

      网友评论

          本文标题:[iOS Swift] Singleton——单例模式的使用与理

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