1- (void) Viewdidload2 {3 [Super Viewdidload];4 5 [self test]; 6 }7 8- (void) Test9 {TenXzmusictool *tool =[[Xzmusictool alloc] init]; OneXzmusictool *tool2 =[[Xzmusictool alloc] init]; AXzmusictool *tool3 =[Xzmusictool Sharedmusictool]; -Xzmusictool *tool4 =[Xzmusictool Sharedmusictool]; - the //copy has the potential to produce new objects - //The copy method is called internally-Copywithzone: -Xzmusictool *TOOL5 =[tool4 copy]; - +NSLog (@"%@ %@ %@ %@ %@", tool, Tool2, Tool3, Tool4, TOOL5); -}
[[Xzmusictool alloc] init];
[Xzmusictool Sharedmusictool];
[Tool4 copy];
All three of these methods guarantee that the object created is the same one.
1 .2 //Lazy Type3 4 #import "XZMusicTool.h"5 6 @implementationXzmusictool7 Static ID_instance;8 9 /**Ten * This method is called internally by the Alloc method One */ A+ (ID) Allocwithzone: (struct_nszone *) Zone - { - if(_instance = = nil) {//prevent frequent lock -up the @synchronized (self) { - if(_instance = = nil) {//prevent creation of multiple -_instance =[Super Allocwithzone:zone]; - } + } - } + return_instance; A } at -+(instancetype) Sharedmusictool - { - if(_instance = = nil) {//prevent frequent lock -up - @synchronized (self) { - if(_instance = = nil) {//prevent creation of multiple in_instance =[[Self alloc] init]; - } to } + } - return_instance; the } * $- (ID) Copywithzone: (Nszone *) ZonePanax Notoginseng { - return_instance;//now that you can copy, it means that you have created the object. the } + @end
Make a comparison of the following code:
1 @implementationPaymanager2 3+(instancetype) Sharedmanager {
4 Staticdispatch_once_t Oncetoken;5 StaticPaymanager *_instance;
6Dispatch_once (&oncetoken, ^{7_instance =[[Paymanager alloc] init];8 });9 return_instance;Ten } One A @end
Singleton mode-BASIC Implementation 01