IOS design mode-singleton Mode

Source: Internet
Author: User

The Singleton mode is used when a class can only have one instance. Generally, this Singleton mode indicates a physical device, such as a printer, or a virtual resource or system attribute that cannot have multiple instances at the same time, such as an engine or data of a program. It is necessary to use the singleton mode for control.

Purpose of Singleton Mode

1. encapsulate a shared resource

2. Provide a fixed instance Creation Method

3. provides a standard instance access interface

Creation of Singleton Mode

This document uses the singletonclass Singleton mode as an example. First, we need to define a class mysingletonclass.

@interface MySingletonClass:NSObject {    }

And add a class method for it (note that this is not an instance method) + (ID) sharedinstance; a basic implementation method is as follows:

static MySingletonClass *sharedCLDelegate = nil;+(MySingletonClass *)sharedInstance{    @synchronized(self) {        if(sharedCLDelegate == nil) {            [[[self class] alloc] init]; //   assignment   not   done   here        }    }    return sharedCLDelegate;}

In the above Code (the keyword @ synchronized is used to ensure the thread-level security of our Singleton, which can be applied to multithreading mode .) The static variable sharedcldelegate is used to store the pointer of a Singleton, and forces all accesses to this variable to use the class method + (ID) sharedinstance.
+ (ID) the instance is created when the first call is made to the sharedinstance. It is worth noting that the above Code uses [[selfclass] alloc] instead
[Mysingletonclass alloc], these two statements have the same effect in general, but here we do this to make better use of the Nature of OOP, [selfclass] You can dynamically search for and determine the type of the class to facilitate subclass of the class.

Control of Instantiation

In order to fully implement the single-State nature of the instance, some measures must be taken to prevent the instance from being created multiple times. + (ID) sharedinstance controls the creation and access of a single instance, but it does not control the code in other places to use the alloc method to create more instances, therefore, we need to reload any method that involves allocation, including
+ New, + alloc, + allocwithzone:,-copywithzone :,
And-mutablecopywithzone: In addition, + (ID) sharedinstance needs to be slightly modified.

+ (ID) hiddenalloc {return [Super alloc] ;}+ (ID) alloc {nslog (@ "% @: Use + sharedinstance instead of + alloc ", [[self class] Name]); Return nil;} + (ID) New {return [self alloc];} + (ID) allocwithzone :( nszone *) zone {return [self alloc];}-(ID) copywithzone :( nszone *) Zone {//-copy inherited from nsobject CILS-copywithzone: nslog (@ "mysingletonclass: attempt to-copy may be a bug. "); [self retain]; return self;}-(ID) mutablecopywithzone :( nszone *) Zone {//-mutablecopy inherited from nsobject CILS-mutablecopywithzone: return [self copywithzone: zone] ;}+ (ID) sharedinstance modified as follows: + (mysingletonclass *) sharedinstance {@ synchronized (Self) {If (sharedcldelegate = nil) {[[self class] hiddenalloc] init]; // assignment not done here} return sharedcldelegate ;}

If the subclass of the class is not considered, the + hiddenalloc method can be omitted. Because we use [selfclass] for Dynamic Identification of types, we use [[selfclass]
Hiddenalloc] can avoid calling the overloaded alloc method. In addition, hiddenalloc provides an opportunity to call the original alloc Method for possible subclass. The previously overloaded alloc method only provides a log and returns nil. The copying method simply adds the retain count and does not return a new instance. This also reflects the nature of the singleton model, because technically speaking, copying a singleton is incorrect (because it is a "Singleton ") therefore, an error message is provided in the copywithzone method. Of course, an exception can be thrown.

Destruction of a single instance

Usually we call the following method in the-(void) applicationwillterminate :( uiapplication *) application method:

+ (void)attemptDealloc{    if ([sharedCLDelegate retainCount] != 1)        return;    [sharedCLDelegate release];    myInstance = nil;}

It is worth noting that the above attemptdealloc method just tries to release the Singleton. If the retain count is not 1, there are other places to send a retain message to this example. Considering that the life cycle of a singleton mode is the end of the entire program. Therefore, there is no need to send a retain message to this Singleton anywhere in the program, even if there is a reference to this Singleton. Instead, the sharedinstance method is called to reference this singleton. This is safe and conforms to the technical meaning of the singleton mode.

Application of Singleton mode in IOS

Several Classes in IOS use the singleton mode, such as nsapplication, nsfontmanager, nsdocumentcontroller, nshelpmanager, nsnull, nsprocessinfo, nsscriptexecutioncontext, and nsuserdefaults.

If there are any mistakes in this article, please correct them and make progress together. Thank you!

Related Article

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.