前言
- 单例对象能够被整个程序所操作。对于一个单例类,无论初始化单例对象多少次,也只能有一个单例对象存在,并且该对象是全局的,能够被整个系统访问到。
单例类的创建
1.1 单例类的创建 1
-
单例类的创建
class SingleClass1 { var text:String = "default" class var sharedInstance: SingleClass1 { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: SingleClass1? = nil } dispatch_once(&Static.onceToken) { Static.instance = SingleClass1() } return Static.instance! } }
-
单例类对象的调用
var single1:SingleClass1 = SingleClass1.sharedInstance single1.text = "QQ" var str = SingleClass1.sharedInstance.text println(str)
1.2 单例类的创建 2
-
单例类的创建
class SingleClass2 { var text:String = "default" class var sharedInstance: SingleClass2 { struct Static { static let instance = SingleClass2() } return Static.instance } }
-
单例类对象的调用
var single2:SingleClass2 = SingleClass2.sharedInstance single2.text = "QQ" var str = SingleClass2.sharedInstance.text println(str)
1.3 单例类的创建 3
-
单例类的创建
private let sharedKraken = SingleClass3() class SingleClass3 { var text:String = "default" class var sharedInstance: SingleClass3 { return sharedKraken } }
-
单例类对象的调用
var single3:SingleClass3 = SingleClass3.sharedInstance single3.text = "QQ" var str = SingleClass3.sharedInstance.text println(str)
1.4 单例类的创建 4
-
单例类的创建
class SingleClass4 { var text:String = "default" // This prevents others from using the default '()' initializer for this class. static let sharedInstance = SingleClass4() private init() {} }
-
单例类对象的调用
var single4:SingleClass4 = SingleClass4.sharedInstance single4.text = "QQ" var str = SingleClass4.sharedInstance.text println(str)