iOS common design pattern--Singleton design mode

Source: Internet
Author: User

A detailed example of a single design pattern

    • A detailed example of a single design pattern
      • Basic concepts
      • Case of using singleton mode in iOS
        • Basic steps for creating a singleton pattern in a non-ARC environment
        • Specific code implementations for non-ARC environments
        • Basic steps for creating a singleton pattern in an arc environment

Basic concepts

Singleton mode is a kind of common software design pattern. In its core structure, it contains only a special class called a singleton class. The singleton mode ensures that there is only one instance of a class in the system and that the instance is easily accessible to the outside world

Case of using singleton mode in iOS

1. If creating an object consumes a lot of system resources, then singleton mode is used, because only one instance is needed, which saves alloc time

2. In iOS development, if many modules are using the same variable, if you put the variable into a singleton class, all calls to access the variable become easy, otherwise, it can only be passed to another module through one module, which increases the risk and complexity

Basic steps for creating a singleton pattern in a non-ARC environment

1. Declare a static instance of a singleton object and initialize it to nil
2. Declares a factory method of a class, generates an instance of the class, and generates only one
3. Overwrite the Allcowithzone method to ensure that the user does not produce an extra object when Alloc

4. Implement the Nscopying protocol, overriding the Release,autorelease,retain,retaincount method to ensure that only one instanced object

5. In a multithreaded environment, note the use of the @synchronized keyword

Specific code implementations for non-ARC environments
#import <Foundation/Foundation.h>  @interface UserContext : nsobject @property(nonatomic, retain)NSString*username;@property(nonatomic, retain)NSString*email;+ (ID) Shareduserdefault;@end////USERCONTEXT.M//Singledemo////Created by Andyyang on 9/30/13.//Copyright (c) Andyyang. All rights reserved.//#import "UserContext.h" StaticUserContext *singleinstance=Nil; @implementation UserContext +(ID) shareduserdefault{if(singleinstance==Nil) {@synchronized ( Self)        {if(singleinstance==Nil) {singleinstance=[[[ SelfClass] alloc] init]; }        }    }returnSingleInstance;} + (ID) Allocwithzone: (Nszone *) zone; {if(singleinstance==Nil) {singleinstance=[SuperAllocwithzone:zone];}returnSingleInstance;} -(ID) Copywithzone: (Nszone *) zone{returnSingleInstance;} -(ID) retain{returnSingleInstance;} -(OneWayvoid) release{}-(ID) autorelease{returnSingleInstance;} -(Nsuinteger) retaincount{returnUint_max;}@end#import <Foundation/Foundation.h> #import "UserContext.h" intMainintargcConst Char* argv[]) {@autoreleasepool {UserContext *usercontext1=[usercontext shareduserdefault];        UserContext *usercontext2=[usercontext Shareduserdefault];        UserContext *usercontext3=[[usercontext alloc] init]; UserContext *usercontext4=[usercontext1 Copy];//Insert code here ...        NSLog(@"Hello, world!."); }return 0;}
Basic steps for creating a singleton pattern in an arc environment
+ (instantClass *)sharedClient {staticnil;staticdispatch_once_t onceToken;dispatch_once(&onceToken, ^{_sharedClient = [[instantClass alloc] init];});return _sharedClient;}

This approach has many advantages:
1 Thread Safety
2 Good to meet static analyzer requirements
3 and Auto Reference count (ARC) compatible
4 requires only a small amount of code

iOS common design pattern--Singleton design mode

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.