Singleton mode-BASIC Implementation 01

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.