[Go] JavaScript singleton mode

Source: Internet
Author: User

Defined

Ensure that a class has only one instance and provides a global access point to access it.

Scenarios used in singleton mode

such as thread pool, global cache, and so on. The Window object of the browser we are familiar with is a singleton, and in JavaScript development, our implementations often use a singleton for this object that requires only one.

Implementing a singleton mode (opaque)

In general, we implement the Singleton, using a variable to flag the current class has already created the object, if the next time you get an instance of the current class, directly return the object created before. The code is as follows:

Define a classfunctionSingleton (Name) {THIS.name = name;This.instance =null;}A method of the prototype extension class GetName () Singleton.prototype.getName =functionconsole.log (this.name)};< Span class= "Hljs-comment" >//gets an instance of the class singleton.getinstance =  function (name) {if (! this.instance) {this.instance = new Singleton (name);} return this.instance}; //Get Object 1var a = singleton.getinstance ( //Get Object 2var B = singleton.getinstance ( //for comparison console.log (a = = B);      

We can also use closures to implement:

functionSingleton (Name) {THIS.name = name;}A method of the prototype extension class GetName () Singleton.prototype.getName =function) {Console.log (THIS.name)};Gets the instance of the class Singleton.getinstance = (functionvar instance = null; return function ( name) {if (! this.instance) {this.instance = new Singleton (name);} return this.instance}) (); //Get Object 1var a = singleton.getinstance ( //Get Object 2var B = singleton.getinstance ( //for comparison console.log (a = = B);      

This singleton implementation of the method of acquiring objects is often seen in the form of novices, which is simple to get objects, but is not transparent in this way. It is not good to know that a person can Singleton.getInstance() get an object and not know the implementation of the code that needs to be studied. This is not the same as our common use of new keywords to get objects, the actual significance is not significant.

Implementing a singleton pattern (transparent)
var Singleton = (function){var instance;var Createsingleton =function (Name) {THIS.name = name;if (instance) {return instance; }Print Instance NameThis.getname ();//instance = this; //return instance; return instance = this;} //get the name of the instance CreateSingleton.prototype.getName = function (console.log ( this.name)} return Createsingleton;}) (); //Create instance Object 1var a = new Singleton ( Span class= "hljs-string" "a"); //Create instance Object 2var B = new Singleton ( Span class= "hljs-string" > ' B '); console.log (a===b);           

This singleton pattern I used once, but very awkward to use, I have seen others in this way to achieve the effect of merry, because merry in our application of the vast majority of only one.

Here's why it doesn't feel right, because there are two things done in this single constructor, one creating an object and printing the instance name, and the other guaranteeing that there is only one instance object. Such a large amount of code is not easy to manage, should try to do a single job.

We usually change the code to look like this:

Single-instance constructorsfunctionCreatesingleton (Name) {THIS.name = name;This.getname ();};Gets the name of the instance CreateSingleton.prototype.getName =function) {Console.log (THIS.name)};//Singleton object var Singleton = (function (var instance; return function ( Name) {if (!instance) {instance = new Createsingleton (name);} Span class= "Hljs-keyword" >return instance; }})(); //Create instance Object 1var a = new Singleton ( Span class= "hljs-string" "a"); //Create instance Object 2var B = new Singleton ( Span class= "hljs-string" > ' B '); console.log (a===b);           

This implementation is familiar to us, and we often use intermediate classes in development to implement special functions that the original class does not have. Some people call this implementation a proxy, which is indeed an application of the singleton pattern, which will be explained later in the proxy mode.

Having said that, we're still talking about the traditional singleton pattern, so what's a single-case pattern with JavaScript in it?

JavaScript single-case mode

In our development, many students may not know what the single case is, how to use the singleton, but they write the code just meet the requirements of the singleton model. If you want to implement a landing pop-up window, the login window will pop up regardless of the page or click the login button in the same place on the page. Some students will write a global object to implement the Landing window function, yes, this can actually achieve the required landing effect, but also meet the requirements of the singleton mode, but this implementation is actually a coincidence, or a beautiful mistake. Because global objects, or global variables, exactly conform to the Singleton, are globally accessible and unique. But as we all know, global variables can be overwritten, especially for junior developers, at first, regardless of the basic definition of what is generally global, the advantage is convenient access, the disadvantage is not to pay attention to the cause of conflict, especially in the work of a team of large projects, So mature experienced developers minimize global claims.

In the development of our general approach to avoid global variable pollution is as follows:

    • Global namespaces
    • Using closures

What they have in common is that they can define their own members and store data. The difference is that all methods and properties of the global namespace are public, and closures can be privatized for methods and properties.

Lazy Singleton mode

To tell the truth, before I made up my mind to study design patterns, I didn't know that the singleton model was also divided into inert singleton mode, until I looked at the "Jvascript design pattern and development practice" of the Great God before I learned that there are also lazy singleton mode, then what is the Lazy singleton mode? Before I say lazy singleton mode, allow me to say one we all know lazyload loading image, it is lazy loading, only if the DOM element containing the picture resource appears in the visual area of the media device, the image resource will be loaded, this loading mode is lazy loading And there is the pull refresh resource is also lazy loading, when you trigger a drop-down Refresh event resource will be loaded etc. The principle of lazy singleton mode is the same, only when the instance object is triggered, the instance object is created. This method of instance object creation is necessary in development.

Just as we've just started with Singleton.getInstance creating instance objects, although this approach implements lazy Singleton, it's not a good way to implement it, as we've just started. Here's a good way to implement it.

The mask layer believes that everyone is not unfamiliar with it. It is more common in development, and it is simpler to implement. The way they are implemented in everyone's development is different. The best way to implement this is to use a singleton pattern. Some people realize to add a div directly to the page and then set display to none, so that whether we use the Mask Layer page will load this div, if it is multiple pages is the cost of multiple div, some people use JS to create a div, when needed to add it to the body , if you do not need to delete, so frequent operation of the DOM on the performance of the page is also a kind of consumption; others are based on the previous one with an identifier to judge, when the mask layer is the first time to add to the page, do not need to hide, if it is not the previous one added.

The implementation code is as follows:

Html<button id="BTN" >click it</button>Jsvar createmask = (function() {var mask;Returnfunction() {if (!mask) {Creating DIV elementsvar mask = document.createelement ( ' div '); //set style mask.style.position =  ' fixed '; mask.style.top =  ' 0 '; Mask.style.right =  ' 0 '; mask.style.bottom =  ' 0 '; mask.style.left =  ' 0 '; mask.style.opacity =  ' none '; Document.body.appendChild (mask); } return Mask;}) ();d Ocument.getelementbyid ( ' btn '). onclick = function () {var Masklayer = CreateMask (); MaskLayer.style.display =         

We found that masking layers are not used alone in development, and masking layers and popups are often used together, and we mentioned that landing pop-up windows are best suited for using singleton mode implementations. So are we going to make a copy of the above code? Of course, we have a good way to do that is to separate the part of the code in the above example from the invariant part.

The code is as follows:

var singleton =functionFN) {var instance;Returnfunction) {return Instance | | (Instance = fn.apply (Thisarguments)); }};Creating a matte Layervar createmask =function){Creating DIV elementsvar mask =Document.createelement (' Div ');Set Style Mask.style.position =' Fixed '; Mask.style.top =' 0 '; Mask.style.right =' 0 '; Mask.style.bottom =' 0 '; Mask.style.left =' 0 '; Mask.style.opacity =' o.75 '; Mask.style.backgroundColor =' #000 '; Mask.style.display =' None '; Mask.style.zIndex =' 98 ';Document.body.appendChild (mask);Click Hide Matte Layer Mask.onclick =function){This.style.display =' None '; }return mask;};Create a login windowvar createlogin =function) {Creating DIV elementsvar login =Document.createelement (' Div ');Set Style Login.style.position =' Fixed '; Login.style.top =' 50% '; Login.style.left =' 50% '; Login.style.zIndex =' 100 '; Login.style.display =' None '; Login.style.padding =' 50px 80px '; Login.style.backgroundColor =' #fff '; Login.style.border =' 1px solid #ccc '; Login.style.borderRadius = ' login it '; document.body.appendchild (login); return login;}; document.getelementbyid ( ' btn '). onclick = function (var Omask = Singleton (Createmask) (); OMask.style.display =  ' block '; var ologin = Singleton (Createlogin) (); oLogin.style.display =  Block '; var w = parseint (ologin.clientwidth); var h = parseint (ologin.clientheight);}    

In the above implementation of the Singleton mode of the lazy implementation of the partial extraction, the implementation of the lazy implementation of code reuse, in which the use of change changes in the FN of the this point, using || the budget to simplify the writing of code.

[Go] JavaScript singleton mode

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.