Swift singleton && Lazy initializition

偷个懒,看到了个比较靠谱的答案,直接复制过来了。

原网址:http://stackoverflow.com/questions/24024549/dispatch-once-singleton-model-in-swift

From my short experience with Swift there are three approaches to implement the Singleton pattern that support lazy initialization and thread safety.

These approaches might change or become redundant as the language matures.

Global constant

private let _SingletonSharedInstance = Singleton()

class Singleton  {
    class var sharedInstance : Singleton {
        return _SingletonSharedInstance
    }
}

We use a global constant because class constants are not yet supported.

This approach supports lazy initialization because Swift lazily initializes global constants (and variables), and is thread safe by virtue of let.

Nested struct

class Singleton {
    class var sharedInstance : Singleton {
        struct Static {
            static let instance : Singleton = Singleton()
        }
        return Static.instance
    }
}

Unlike classes, structs do support static constants. By using a nested struct we can leverage its static constant as a class constant.

The nested struct is the approach I recommend until class constants are supported.

dispatch_once

The traditional Objective-C approach ported to Swift. I‘m fairly certain there‘s no advantage over the nested struct approach but I‘m putting it here anyway as I find the differences in syntax interesting.

class Singleton {
    class var sharedInstance : Singleton {
        struct Static {
            static var onceToken : dispatch_once_t = 0
            static var instance : Singleton? = nil
        }
        dispatch_once(&Static.onceToken) {
            Static.instance = Singleton()
        }
        return Static.instance!
    }
}

See this GitHub project for unit tests.

Swift singleton && Lazy initializition

时间: 2024-08-30 11:46:52

Swift singleton && Lazy initializition的相关文章

设计模式 单件-Singleton

单件模式 Singleton 什么时候使用?当需要独一无二的对象时,请想起他. 举例:线程池(threadpool),缓存(cache),对话框,处理偏好设置和注册表(registry)的对象,驱动程序对象. 无需具体例子,先看类图:包含一个private的自己的实例.private的构造函数,确保无法在类以外创建.在getInstance()中检测私有实例是否创建,未则创建,若已存在则直接返回. 看代码更好理解记忆. 经典实现方式 Typical Singleton public class

单例模式(Singleton)的6种实现

from:http://www.cnblogs.com/rush/archive/2011/10/30/2229565.html 1.1.1 摘要 在我们日常的工作中经常需要在应用程序中保持一个唯一的实例,如:IO处理,数据库操作等,由于这些对象都要占用重要的系统资源,所以我们必须限制这些实例的创建或始终使用一个公用的实例,这就是我们今天要介绍的--单例模式(Singleton). 使用频率 高 单件模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点. 1.1.2

ios -- 教你如何轻松学习Swift语法(三) 完结篇

一.自动引用计数 1.自动引用计数工作机制 1.1 swift和oc一样,采用自动引用计数来管理内存 1.2 当有强引用指向对象,对象的引用计数 +1 , 强引用消失,自动计数 -1 1.3 如果对象的引用计数为0 , 那么该对象会被销毁 2.循环引用 2.1 什么是循环引用? 两个(或多个)对象互相强引用 2.2 循环引用对项目有什么影响 循环引用会让对象不会被销毁,一直保存在内存中,可能导致项目运行不畅 2.3 怎么解决强引用问题? 只需要让其中一个对象对另外一个对象的引用变为弱引用即可 在

[原] blade中singleton的实现

最近看了龚大大KalyGE中的singleton, 觉得非常不错(C++中线程安全并且高效的singleton). 可惜blade的代码都是C++03的, 没有使用C++11的任何特性. 笔者对于singleton也有些经验, 不过由于业余写代码本来就时间不够(blade在6年内堆了近20W行代码), 所以笔记记得非常少. 最近几个月业余没有写代码了, 所以有时间把blade在开发中遇到的问题贴出来. 而C++11虽然很爽很方便, 但是目前还没有加入支持的打算. 为了方便分析, 列出两种方式的s

Singleton Design Pattern

The Singleton pattern is one of the simplest design patterns, which restricts the instantiation of a class to ONLY ONE object. A singleton class only allows a single instance of itself to be created, and usually gives simple access to that instance.

C# 单例模式(Singleton Pattern)

(新手写博客,主要是对自己学习的归纳总结.会对很多小细节详解.) 单例模式的定义: 确保一个类只有一个实例,并提供一个全局访问点. 首先实例大家应该都明白就是类生成对象的过程简单的就是String s=new String(),则s就是个实例. Q:如何只生成一个实例? A:1)首先必须将构造函数变为私有从而防止其他类实例化,并且只能有一个构造函数.因为系统会默认一个无参构造函数,而且默认public访问修饰符. 所以必须写一个私有无参让默认无效.(通常单例模式都是不带形参的) 2)在该类中声明

[Swift]Day10:属性

属性 延时存储属性 Objective-C 的做法 有时候我们需要延时加载属性,在 Objective-C 中可以通过重写 getter 方法实现: @property (nonatomic, strong) NSMutableArray *players; - (NSMutableArray *)players { if (!_players) { _players = [[NSMutableArray alloc] init]; } return _players; } Swift 的新关键

Implementing the Singleton Pattern in C#

Implementing the Singleton Pattern in C# Table of contents (for linking purposes...) Introduction Non-thread-safe version Simple thread safety via locking Double-checked locking Safety through initialization Safe and fully lazy static initialization

设计模式-5-单例模式

说明:通过对自身的调用,在全局只能创建一个 sealed class Singleton { private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton()); public static Singleton Instance { get { return lazy.Value; } } private Singleton() { index = 0; } pub