swift Swift中单例模式的示例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift Swift中单例模式的示例相关的知识,希望对你有一定的参考价值。

//XCode Playground Friendly

/**
 Singleton Pattern - Ensures that only one instance of a object exists in the application context
 usefull for things that will have a global context across the app.
 Ex: An internet connection, Credentials, etc.
 
 * Can only be used for reference types.
 */

/*
 Implementation using private initializer - This is threadsafe and the simplest implementation
 */
class Singleton {
    static let sharedInstance = Singleton() //<- Singleton Instance
    var instanceNum: Int = 0
    
    private init() { /* Additional instances cannot be created */ }
}

/* Test Code */
let instance1 = Singleton.sharedInstance
let instance2 = Singleton.sharedInstance

instance1.instanceNum = 1
instance2.instanceNum = 2
assert(instance1.instanceNum == 2)

以上是关于swift Swift中单例模式的示例的主要内容,如果未能解决你的问题,请参考以下文章

Objective-C中单例模式的实现-备

swift语言实现单例模式

Swift实战-单例模式

iOS开发入门——17条 Swift 最佳实践规范(下)

设计模式(Swift) - 单例模式备忘录模式和策略模式

swift实现单例的四种方式