JS Single-Case mode

Source: Internet
Author: User

Singleton mode (Singleton), which guarantees that a class has only one instance, and provides a global access point to access it.

Usually we can have a global variable that makes an object accessible, but it doesn't prevent you from instantiating multiple objects. One of the best ways is to have the class itself responsible for preserving its only instance. This class guarantees that no other instance can be created, and it can provide a way to access the instance.

In order to help you better understand the singleton model, we can combine the following class diagram to understand, as well as the subsequent analysis of the implementation of the singleton mode of thinking:

Here's a look at the specific implementation code (you'll be surprised to see that!) ):

  /// <summary>    ///the implementation of single-case pattern/// </summary>     Public classSingleton {//define a static variable to hold an instance of the class        Private StaticSingleton uniqueinstance; //define private constructors so that the outside world cannot create instances of that class        PrivateSingleton () {}/// <summary>        ///defining public methods provides a global access point, and you can also define public properties to provide global access points/// </summary>        /// <returns></returns>         Public StaticSingleton getinstance () {//created if an instance of the class does not exist, or is returned directly            if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }            returnuniqueinstance; }    }

The implementation of the above singleton mode is really perfect on a single thread, however multiple singleton instances are obtained in multi-threaded situations, because two threads are judged when two threads are running the GetInstance method at the same time (Uniqueinstance ==null) This condition returns True, at which point two threads will create an instance of Singleton, which would violate our singleton schema, since the implementation above would run multiple threads to execute, that Our multi-threaded solution is to make the GetInstance method run only one thread at a time , that is, our thread synchronization problem (for thread synchronization You can also refer to my thread synchronization of the article), the specific solution multithreading code is as follows:

/// <summary>    ///the implementation of single-case pattern/// </summary>     Public classSingleton {//define a static variable to hold an instance of the class        Private StaticSingleton uniqueinstance; //define an identity to ensure thread synchronization        Private Static ReadOnly ObjectLocker =New Object(); //define private constructors so that the outside world cannot create instances of that class        PrivateSingleton () {}/// <summary>        ///defining public methods provides a global access point, and you can also define public properties to provide global access points/// </summary>        /// <returns></returns>         Public StaticSingleton getinstance () {//when the first thread runs here, the locker object is "locked" at this point ,//When the second thread runs the method, it first detects that the locker object is a "lock" state, and the thread suspends waiting for the first line threads unlocked//after the lock statement finishes running (that is, after the thread finishes running) The object is "unlocked"            Lock(locker) {//created if an instance of the class does not exist, or is returned directly                if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }            }            returnuniqueinstance; }    }

The above solution does solve the problem of multithreading, but the above code is not necessary for each thread to judge whether the instance exists after locker locking the thread helper object, because when the first thread creates an instance of the class, The following thread at this time only need to directly judge (Uniqueinstance==null) is false, at this time there is no need to lock up the thread helper objects before going to judge, so the above implementation method adds additional overhead, loss of performance, in order to improve the implementation of the above defects, We only need to add a sentence (uniqueinstance==null) in front of the lock statement to avoid the additional overhead of locking, this implementation we call it "double lock", the following concrete look at the implementation of the Code:

/// <summary>    ///the implementation of single-case pattern/// </summary>     Public classSingleton {//define a static variable to hold an instance of the class        Private StaticSingleton uniqueinstance; //define an identity to ensure thread synchronization        Private Static ReadOnly ObjectLocker =New Object(); //define private constructors so that the outside world cannot create instances of that class        PrivateSingleton () {}/// <summary>        ///defining public methods provides a global access point, and you can also define public properties to provide global access points/// </summary>        /// <returns></returns>         Public StaticSingleton getinstance () {//when the first thread runs here, the locker object is "locked" at this point ,//When the second thread runs the method, it first detects that the locker object is a "lock" state, and the thread suspends waiting for the first line threads unlocked//after the lock statement finishes running (that is, after the thread finishes running) The object is "unlocked"//double locking requires just one sentence.            if(Uniqueinstance = =NULL)            {                Lock(locker) {//created if an instance of the class does not exist, or is returned directly                    if(Uniqueinstance = =NULL) {uniqueinstance=NewSingleton (); }                }            }            returnuniqueinstance; }    }

After understanding the singleton pattern, the rookie went on to ask: Is there an implementation of Singleton mode in the. NET Framework class library?

After viewing,. NET class library does exist in a singleton pattern implementation class, but the class is not public, the following is a concrete look at the class implementation (the class specifically exists in the System.dll assembly, the namespace is system, you can use the Reflection tool reflector to see the source):

//The class is not a public class//but the implementation of this class applies a singleton pattern    Internal Sealed classSR {Private StaticSR Loader; InternalSR () {}//The main reason is that the class is not public, so this entire access point is also defined as private.//but thought still used the idea of a singleton pattern .        Private StaticSR Getloader () {if(Loader = =NULL) {SR SR=NewSR (); Interlocked.compareexchange<SR> (refLoader, SR,NULL); }            returnloader; }        //The Getloader method is called in this public method .         Public Static ObjectGetObject (stringname) {SR Loader=Getloader (); if(Loader = =NULL)            {                return NULL; }            returnloader.resources.GetObject (name, Culture); }    }

JS Single-case mode:

varCreateloginlayer = (function(){    varDiv; return function(){        if(!Div) {Div= document.createelement (' div '); Div.innerhtml= ' I am logged in to the floating window '; Div.style.display= ' None ';        Document.body.appendChild (DIV); }        returnDiv; }})(); Call: document.getElementById (' Loginbtn '). onclick =function(){                varLoginlayer =Createloginlayer (); LoginLayer.style.display= ' Block '; }; 

JS generic Lazy Single-column:

varGetsingle =function(FN) {varresult; return function(){        returnResult | | (Result = Fn.apply ( This, arguments)); }};varCreateloginlayer =function(){    vardiv = document.createelement (' div '); Div.innerhtml= ' I am logged in to the floating window '; Div.style.display= ' None ';    Document.body.appendChild (DIV); returnDiv;};varCreatesingleloginlayer =Getsingle (Createloginlayer);d Ocument.getelementbyid (' Loginbtn '). Onclcik =function(){    varLoginlayer =Createsingleloginlayer (); LoginLayer.style.display= ' Block ';}; varCreatesingleiframe = Getsingle (function(){    variframe = document.createelement (' iframe ');    Document.body.appendChild (IFRAME); returniframe;}); document.getElementById (' Loginbtn '). onclick =function(){    varLoginlayer =Createsingleiframe (); LOGINLAYER.SRC= ' http://baidu.com ';}; 

JS Single-Case 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.