標籤:
1 - (void)viewDidLoad 2 { 3 [super viewDidLoad]; 4 5 [self test]; 6 } 7 8 - (void)test 9 {10 XZMusicTool *tool = [[XZMusicTool alloc] init];11 XZMusicTool *tool2 = [[XZMusicTool alloc] init];12 XZMusicTool *tool3 = [XZMusicTool sharedMusicTool];13 XZMusicTool *tool4 = [XZMusicTool sharedMusicTool];14 15 // copy 有可能會產生新的對象16 // copy方法內部會調用- copyWithZone:17 XZMusicTool *tool5 = [tool4 copy];18 19 NSLog(@"%@ %@ %@ %@ %@", tool, tool2, tool3, tool4, tool5);20 }
[[XZMusicTool alloc] init];
[XZMusicTool sharedMusicTool];
[tool4 copy];
以上三種方式都能保證建立出來的對象是同一個.
1 . 2 // 懶漢式 3 4 #import "XZMusicTool.h" 5 6 @implementation XZMusicTool 7 static id _instance; 8 9 /**10 * alloc方法內部會調用這個方法11 */12 + (id)allocWithZone:(struct _NSZone *)zone13 {14 if (_instance == nil) { // 防止頻繁加鎖15 @synchronized(self) {16 if (_instance == nil) { // 防止建立多次17 _instance = [super allocWithZone:zone];18 }19 }20 }21 return _instance;22 }23 24 + (instancetype)sharedMusicTool25 {26 if (_instance == nil) { // 防止頻繁加鎖27 @synchronized(self) {28 if (_instance == nil) { // 防止建立多次29 _instance = [[self alloc] init];30 }31 }32 }33 return _instance;34 }35 36 - (id)copyWithZone:(NSZone *)zone37 {38 return _instance; // 既然可以copy,說明是已經建立了對象。39 }40 @end
列出下面代碼做個比較:
1 @implementation PayManager 2 3 +(instancetype)sharedManager {
4 static dispatch_once_t onceToken; 5 static PayManager *_instance;
6 dispatch_once(&onceToken, ^{ 7 _instance = [[PayManager alloc] init]; 8 }); 9 return _instance;10 }11 12 @end
單例模式-基本實現01