Created
December 11, 2015 11:28
-
-
Save 0xlitf/9f33f081fd95df3ab91b to your computer and use it in GitHub Desktop.
swift实现单例的四种方式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| swift实现单例的四种方式 | |
| 单例模式是设计模式中最简单的一种,甚至有些模式大师都不称其为模式,称其为一种实现技巧,因为设计模式讲究对象之间的关系的抽象,而单例模式只有自己一个对象。 | |
| 当你只需要一个实例的时候需要使用单例,如UIApplication.sharedApplication() 等 ,windows的任务管理器、回收站,都是只能同时存在一个。 | |
| 下面看看swift中的几种实现方式: | |
| 一、一句话搞定,静态常量 | |
| import Foundation | |
| final class SingleOne { | |
| // 实现单例 | |
| static let shareSingleOne = SingleOne() | |
| // 防止外界初始化 | |
| private override init() {} | |
| } | |
| import Foundation | |
| final class SingleOne { | |
| // 实现单例 | |
| static let shareSingleOne = SingleOne() | |
| // 防止外界初始化 | |
| private override init() {} | |
| } | |
| 二、使用dispatch_once可以保证其中的代码只执行一次 | |
| import Foundation | |
| class SingleTwo { | |
| //单例 | |
| static func shareSingleTwo() -> SingleTwo { | |
| struct Singleton{ | |
| static var onceToken : dispatch_once_t = 0 | |
| static var single:SingleTwo? | |
| } | |
| dispatch_once(&Singleton.onceToken,{ | |
| Singleton.single = SingleTwo() | |
| } | |
| ) | |
| return Singleton.single! | |
| } | |
| private override init() {} | |
| } | |
| import Foundation | |
| class SingleTwo { | |
| //单例 | |
| static func shareSingleTwo() -> SingleTwo { | |
| struct Singleton{ | |
| static var onceToken : dispatch_once_t = 0 | |
| static var single:SingleTwo? | |
| } | |
| dispatch_once(&Singleton.onceToken,{ | |
| Singleton.single = SingleTwo() | |
| } | |
| ) | |
| return Singleton.single! | |
| } | |
| private override init() {} | |
| } | |
| 三、利用全局常量 | |
| import Foundation | |
| // 全局的常量 | |
| private let single = SingleThree() | |
| final class SingleThree { | |
| static var sharedInstance : SingleThree { | |
| return single | |
| } | |
| private override init() {} | |
| } | |
| import Foundation | |
| // 全局的常量 | |
| private let single = SingleThree() | |
| final class SingleThree { | |
| static var sharedInstance : SingleThree { | |
| return single | |
| } | |
| private override init() {} | |
| } | |
| 四、在方法内定义静态常量 | |
| import Foundation | |
| final class SingleFour { | |
| static var sharedInstance : SingleFour { | |
| struct Static { | |
| static let instance : SingleFour = SingleFour() | |
| } | |
| return Static.instance | |
| } | |
| private override init() {} | |
| } | |
| import Foundation | |
| final class SingleFour { | |
| static var sharedInstance : SingleFour { | |
| struct Static { | |
| static let instance : SingleFour = SingleFour() | |
| } | |
| return Static.instance | |
| } | |
| private override init() {} | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment