A probe into a single case model

Source: Internet
Author: User

oc/c++ Exploration of single case pattern

Previously wrote OC in the single case is very fixed, has been written so, and then I put it in the shortcut code block, as long as the input singleton directly output this code

+ (Instancetype) instance{StaticClass *sharedinstance =Nil;Static dispatch_once_tOncetoken;dispatch_once(&oncetoken, ^{sharedinstance = [[ SelfALLOC] init]; });returnSharedinstance;}

been written so, and did not pay attention to the internal implementation
These two days have been reviewing C + +, and then saw the C + + singleton mode, found that the internal implementation is still very fastidious

First look at the OC
This method was written down when I first learned OC.
void dispatch_once( dispatch_once_t *predicate, dispatch_block_t block);

The official document explains that this method allows the code inside the block to execute only once in the lifetime of the application, and if multiple threads are called simultaneously, this function will allow the thread to wait synchronously until the block executes. Only once, incidentally help us to solve the multithreading problem, this is Apple to help us package, the official also recommended to write a single case Method!!

Then look at C + + 's

Class Singleton {Private://ConstructorsSingleton ();//Static object Staticsingleton* instance; Public:Staticsingleton* getinstance {if(Instance = = NULL) Instance =NewSingleton ();returnInstance }}

First, we have to set the constructor to private so that others cannot invoke the constructor method
The static objects and methods of C + + are like class objects and methods of classes in OC, similar to the method that starts with + in OC
Set the instance and GetInstance methods to static so that the class calls directly

This is an implementation method, but does not take into account the thread safety
The getinstance () method should be locked

 static  singleton* getinstance {lock (); //does not implement the locking method here, just to explore a singleton mode  if  (Instance = = NULL) Instance = new  Singleton (); Unlock (); //pseudo }  

Assuming that multiple threads want to acquire instance at the same time, when the first thread is locked, the other thread waits only after a thread threads unlocked (instance has been created) for the second to run, then the second thread with the lock, and then the instance, The instance has been created repeatedly

Further improvement, when the instance has not been created when the need to lock, and so on when the second thread is locked, and then determine whether the instance has been created

static Singleton* getInstance { if(instance == NULL){  lock(); //伪  if(instance == NULL)   instance = new Singleton();  unlock(); //伪 }}

In addition, it is guaranteed that only single cases can be obtained from the Singleton method and cannot be assigned and copied
So we want to declare the assignment and copy method, but do not implement

Singleton(const Singleton&){};Singleton&operator=(const Singleton&){};

You can do that in c++11.

Singleton(constdelete;Singleton&operator=(constdelete;

So this is a good way to implement

Class Singleton {Private://ConstructorsSingleton ();//Static object Staticsingleton* instance;//Assignment and copy methodsSingleton (Constsingleton&) {}; singleton&operator=(Constsingleton&) {}; Public:Staticsingleton* getinstance {if(Instance = = NULL) {lock ();//Pseudo   if(Instance = = NULL) Instance =NewSingleton (); Unlock ();//Pseudo} }}
About static members of a class

In C + +, static members do not belong to any one object of the class, so they are not defined when creating objects of the class, they are not initialized by the constructor of the class, and in general, static members cannot be initialized internally, and each static member must be defined and initialized outside the class, like a global variable. A static member definition is defined in addition to any function and will persist throughout the lifetime of the member.
We can use the entire feature to write a singleton pattern.

class Singleton {private: Singleton(); static Singleton* instance;public: static Singleton* getInstance{  return instance; }}//然后在类外初始化Singleton* Singleton::instance = new Singleton();

This method is more concise and thread-safe, because in addition to the static variables inside the function, the rest of the static variables are created before the main function, single-threaded, and a reference to an answer on the StackOverflow

In C #, you can initialize directly within a class

 PublicSealed class Singleton { Private Singleton() {}Private StaticSingleton instance =NewSingleton (); Public StaticSingleton getinstance {get {returnInstance } }}

This method has better performance than the previous two-lock method
There are better ways to do it in C #

 PublicSealed class Singleton {Singleton () {} Public StaticSingleton getinstance{Get {returnNested.instance; }} Class nested{ static Nested() {} internalStaticReadOnly Singleton instance =NewSingleton (); }}

Nested classes are called when the nested class is used to create instance
I don't know how C + + is implemented because I can't implement in-class initialization instance.
The above methods are referred to from the sword to offer

?

A probe into a single case model

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.