单例模式确保每个指定的类只存在一个实例对象,并且可以全局访问那个实例。一般情况下会使用延时加载的策略,只在第一次需要使用的时候初始化。
在 iOS 中单例模式有
NSUserDefaults.standardUserDefaults() UIApplication.sharedApplication()
UIScreen.mainScreen()
NSFileManager.defaultManager()
另一种情况:需要一个全局类来处理配置文件。
如何使用单例模式
image.png
这是一个日志类,有一个属性 (是一个单例对象) 和两个方法 (sharedInstance() 和 init())。
第一次调用 sharedInstance() 的时候,instance 属性还没有初始化。所以我们要创建一个新实例并且返回。
下一次你再调用 sharedInstance() 的时候,instance 已经初始化完成,直接返回即可。这个逻辑确保了这个类只存在一个实例对象。
swift其他单例形式
//swift 推荐形式
final class Single: NSObject {
static let shared = Single()
private override init() {}
}
//objective-c 推荐形式
+ (id)sharedInstance {
static TestClass *sharedInstance = nil;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedInstance = [[TestClass alloc] init];
});
return sharedInstance;
}