Single-instance design mode for iOS development (full and correct version)

Source: Internet
Author: User

The meaning of a singleton is literally knows, and the so-called Singleton is to ensure that only one instance of an object is created during the program's run. Can be used in resources that need to be used extensively or repeatedly, such as our common network request classes, tool classes, and other management classes. For example, my iOS development common system singleton [uiapplication Sharedapplication], [Nsuserdefaults standarduserdefaults] and so on. In iOS development, Singleton mode is a very useful design pattern. For example, a UML class diagram of a simple case pattern.

The role of using a singleton model

It guarantees that a class can have at most one instance during a program's run, that is, the object instance occupies only one copy of the memory resource.

Three points of the singleton pattern:

1. There is only one instance of the class;

2. The class must be able to create this instance on its own;

3. The class must be able to provide this instance to the entire system on its own.

Third, why the need to use a single case

1. Save memory overhead. If an object needs to be used by more than one other object, consider using a singleton, because the class uses only one copy of the memory resource.

2. Using a singleton, you can ensure that other classes get only one copy of the class ( variable value ).

Iv. advantages and disadvantages of a single case model

Advantages

1. Provides controlled access to the unique instance.

2, because there is only one object in the system memory, so it can save system resources, for some of the objects need to be created and destroyed frequently the singleton pattern can undoubtedly improve the performance of the system.

3. Because the singleton pattern class controls the instantiation process, the class can be more flexible in modifying the instantiation process.

Disadvantages

1, because there is no abstraction layer in the simple interest mode, the expansion of the Singleton class has great difficulty.

2, the single-case category of excessive responsibility, to a certain extent, contrary to the "single principle of responsibility."

Five, the realization of a single case

Basic steps:

(1) To create a static instance for a singleton object, can be written as a global, can also be implemented in the class method, and initialized to nil;

  (2) implement an instance construction method to check if the static instance declared above is nil, and if so, create and return an instance of this class;

(3) Rewrite the Allocwithzone method to ensure that other people directly use Alloc and Init to try to acquire a new strength without creating a new instance;

(4) the appropriate implementation of Copywithzone,mutablecopywithzone, non-arc also need to achieve release and Autorelease method .

Let's create a new singleton class, implemented in Singleton.h as follows :

@interface Singleton:nsobject     + (Singleton *) sharedinstance;     @end

Add the following to SINGLETON.M:

@implementation Singleton     Static Singleton * Sharedsingleton = nil;     + (Singleton *) sharedinstance  {      if (Sharedsingleton = = nil)          {= [[ Singleton alloc] init];      }       return Sharedsingleton;  }     @end  

This creates a simple singleton pattern, which is actually implemented by some programmers, but in fact it is not a "strict" version, in practice, if we create objects using methods such as Alloc,copy, a new instance will still be created. Also, multiple instances are created when multithreading is accessed concurrently, so it is non-thread safe.

Here's what I've done to improve the SINGLETON.M:

@implementationSingletonStatic IDSharedsingleton =Nil;+ (ID) Allocwithzone: (struct_nszone *) Zone {if(_instace = =Nil) {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{Sharedsingleton=[Super Allocwithzone:zone];   }); }returnSharedsingleton;} - (ID) init {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{Sharedsingleton=[Super Init];     }); returnSharedsingleton;} +(instancetype)Sharedinstance
{
Return
}

+ (ID) Copywithzone: (struct _nszone *) zone
{
Return

+ (ID) Mutablecopywithzone: (struct _nszone *
{
Return
}
@end

This is a relatively complete singleton implementation, so that when we init,alloc,copy,mutablecopy, we are guaranteed to create only a single singleton.

Six, the single case to be extracted into a macro

Sometimes we a program will have multiple singleton, if we go to have the above code, it is a bit of trouble, so we can say the above code is defined as a macro, and saved in a new file, and then any need to implement a singleton mode of the class to simply add one or two lines of code.

1. Create a header file Singleton.h and add the following code:

//helps implement a single-case design pattern//implementation of the. h file#defineSingletonh (MethodName) + (instancetype) shared# #methodName;//implementation of the. m file#if__has_feature (OBJC_ARC)//It's Arc .#defineSingletonm (MethodName)Static ID_instace =Nil;+ (ID) Allocwithzone: (struct_nszone *) Zone {if(_instace = =Nil) { Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];}); } return_instace;} - (ID) init {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super init];}); return_instace;} +(instancetype) shared# #methodName {return[[Self alloc] init];} + (ID) Copywithzone: (struct_nszone *) Zone {return_instace;} + (ID) Mutablecopywithzone: (struct_nszone *) Zone {return_instace;}#else //not arc .#defineSingletonm (MethodName)Static ID_instace =Nil;+ (ID) Allocwithzone: (struct_nszone *) Zone {if(_instace = =Nil) { Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super Allocwithzone:zone];}); } return_instace;} - (ID) init {Staticdispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{_instace=[Super init];}); return_instace;} +(instancetype) shared# #methodName {return[[Self alloc] init];} -(OneWayvoid) Release {}- (ID) Retain {returnSelf ;} -(Nsuinteger) retaincount {return 1; } + (ID) Copywithzone: (struct_nszone *) Zone {return_instace;} + (ID) Mutablecopywithzone: (struct_nszone *) Zone {return_instace;}

2. In this way we can easily implement a singleton pattern in a class that needs to implement a singleton pattern, assuming there is a tool class Mjsoundtool. Therefore, you can do this by implementing the singleton pattern.

Header file MJSoundTool.h

#import <Foundation/Foundation.h>#import"Singleton.h"@ Interface//+ (instancetype) Sharedsoundtool;  @end

implementation file MJSOUNDTOOL.M

#import " MJSoundTool.h " @implementation mjsoundtoolsingletonm (Soundtool) @end

is not very convenient, we need to design a single case when you can directly use the single macro file. : Single case Macro Singleton.h. Well, the singleton mode is introduced here.

Single-instance design mode for iOS development (full and correct version)

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.