一做祝、單例的定義
在程序的整個運行過程中,只創(chuàng)建一個對象實例客燕,內(nèi)存地址一直不變,就叫做單例狰贯。
單例模式圖示
二也搓、iOS中的單例
cocoa框架中常用的是:
- UIApplication
- NSNotificationCenter
- NSFileManager
- NSUserDefaults
- NSURLCache
三、單例模式的優(yōu)缺點
優(yōu)點:
1.減少內(nèi)存開支(對象需要頻繁的創(chuàng)建和銷毀)
2.減少系統(tǒng)的性能開銷
3.避免對同一資源的同時讀寫操作涵紊,優(yōu)化和共享資源訪問
缺點:
1.沒有抽象層傍妒,擴展困難,想要擴展就必須要修改代碼
2.職責太重摸柄,違背了“單一職責原則”
3.在多線程中使用單例颤练,需要多該單例成員進行線程互斥處理
四、自定義一個單例類
.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/// 自定義一個單例類
@interface GQSingletonTool : NSObject
/// 初始化方法
+ (instancetype)shareInstance;
@end
.m
一般的寫法(不完美驱负,但是夠用):
#import "GQSingletonTool.h"
@implementation GQSingletonTool
+ (instancetype)shareInstance {
static GQSingletonTool *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[GQSingletonTool alloc] init];
});
return instance;
}
@end
上面寫法的缺陷嗦玖,在于如果不使用規(guī)定的 shareInstance 方法來初始化,而是采用 alloc init 的話跃脊,就沒法保證生成的是單例的對象了宇挫。
完備的寫法:
#import "GQSingletonTool.h"
@implementation GQSingletonTool
// 初始化(單例方法)
+ (instancetype)shareInstance {
static GQSingletonTool *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[GQSingletonTool alloc] init];
});
return instance;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
return [GQSingletonTool shareInstance];
}
+ (instancetype)alloc {
return [GQSingletonTool shareInstance];
}
- (id)copy {
return self;
}
- (id)mutableCopy {
return self;
}
+ (id)copyWithZone:(struct _NSZone *)zone {
return self;
}
@end