單例模式-用其他方式實現,模式-方式實現
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 <Foundation/Foundation.h>5 6 @interface XZMusicTool : NSObject7 + (instancetype)sharedMusicTool;8 @end
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 /**2 * 餓漢式3 */4 #import <Foundation/Foundation.h>5 6 @interface XZSoundTool : NSObject7 + (instancetype)sharedSoundTool;8 @end
1 // 餓漢式 2 3 #import "XZSoundTool.h" 4 5 @implementation XZSoundTool 6 static id _instance; 7 8 /** 9 * 當類載入到OC運行時環境中(記憶體),就會調用一次(一個類只會載入1次)10 */11 + (void)load12 {13 _instance = [[self alloc] init];14 }15 16 + (id)allocWithZone:(struct _NSZone *)zone17 {18 if (_instance == nil) { // 防止建立多次19 _instance = [super allocWithZone:zone];20 }21 return _instance;22 }23 24 + (instancetype)sharedSoundTool25 {26 return _instance;27 }28 29 - (id)copyWithZone:(NSZone *)zone30 {31 return _instance;32 }33 34 ///**35 // * 當第一次使用這個類的時候才會調用36 // */37 //+ (void)initialize38 //{39 // NSLog(@"HMSoundTool---initialize");40 //}41 @end