保证一个类公有一个实例,并提供一个访问它的全局访问点。
1、使用场景
class SwiftSingleton { class var shared: SwiftSingleton { dispatch_once(&Inner.token) { Inner.instance = SwiftSingleton() } return Inner.instance! } struct Inner { static var instance: SwiftSingleton? static var token: dispatch_once_t = 0 } }
class SwiftSingletonTest: XCTestCase { func testSingleton() { let singleton1 = SwiftSingleton.shared let singleton2 = SwiftSingleton.shared assert(singleton1 === singleton2, "pass") } }
class SwiftSingleton { class var shared: SwiftSingleton { return Inner.instance } struct Inner { static let instance = SwiftSingleton() } }
struct SwiftSingleton { var name: String = "1" static let shared = SwiftSingleton() } var single1 = SwiftSingleton.shared var single2 = SwiftSingleton.shared single2.name = "2" println("------->\(single1.name)") println("------->\(single2.name)")
------->1 ------->2 Program ended with exit code: 0
Swift语言下的单例设计模式实现(SINGLETON),布布扣,bubuko.com
原文:http://blog.csdn.net/g1jun/article/details/30461205