您的位置:首页 > 移动开发 > Swift

Swift-总结单例实现的几种方法

2016-04-14 15:07 405 查看

Swift实现代理的几种方法

1.

class AppManager {
private static let _sharedInstance = AppManager()
class func getSharedInstance() -> AppManager {
return _sharedInstance
}
private init() {} // 私有化init方法
}
//使用方式
AppManager.getSharedInstance()


2.

class AppManager {
static let sharedInstance = AppManager()
private init() {} // 私有化init方法
}
//使用方式
AppManager.sharedInstance


3.

let _SharedInstance = AppManager()
class AppManager  {
class var sharedInstance : AppManager {
return _SharedInstance
}
}
private init() {} // 私有化init方法
}
//使用方式
AppManager.sharedInstance


4.

class AppManager {
class var sharedInstance : AppManager {
struct Static {
static let instance : AppManager = AppManager()
}
return Static.instance
}
}
private init() {} // 私有化init方法
}
//使用方式
AppManager.sharedInstance


5.

class AppManager {
class var sharedInstance : AppManager {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : AppManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = AppManager()
}
return Static.instance!
}
}
private init() {} // 私有化init方法
}
//使用方式
AppManager.sharedInstance


附:为什么需要保证INIT的私有化?

因为只有init()是私有的,才能防止其他对象通过默认构造函数直接创建这个类对象,确保你的单例是真正的独一无二。

因为在Swift中,所有对象的构造器默认都是public,所以需要重写你的init让其成为私有的。这样就保证像如下的代码编译报错,不能通过。

1

2

var a1 = AppManager() //确保编译不通过

var a2 = AppManager() //确保编译不通过
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: