JavaScript Design Pattern Learning four--singleton mode

Source: Internet
Author: User

Definition of a singleton pattern: ensure an instance and provide global access.

Lazy Singleton Definition: objects are created only when they are needed.

In development, some objects often require only one, such as a thread pool, a global cache, a Window object in a browser, and so on.

A singleton in Java

The key is to use a variable to flag whether the object is currently created for a class.

 Public classSingleton {PrivateSingleton () {}Private StaticSingleton single=NULL; //Static Factory Method     Public StaticSingleton getinstance () {if(single =NULL) { single=NewSingleton (); }            returnSingle ; }}

Such a singleton class has a certain "opacity", the user must know that this is a singleton class, cannot create an instance through new XXX, but need to use the Singleton.getinstance method to get the object.

A singleton pattern in JavaScript

According to the characteristics of the singleton mode: 1 Only one instance, 2) provide global access;

1) The Global object arguments in JavaScript undoubtedly conform to the characteristics of Singleton, but the disadvantage is that there will inevitably be a global pollution problem;

2) The following is a general approach to the implementation of a lazy single example

Document.addeventlistener ('domcontentloaded', function () {
Getsingle is a common method of creating a single casevargetsingle=function (FN) {varret; returnfunction () {returnret| | (Ret=fn.apply ( This, arguments)); }; }; //The following is an example of creating a unique landing floating window varCreateloginlayer=function () {varDiv=document.createelement ('Div'); Div.innerhtml='I'm landing on the floating window .'; Document.body.appendChild (DIV); returnDiv; }; varGetsingleloginlayer=Getsingle (Createloginlayer); vardiv1=Getsingleloginlayer (); varDiv2=Getsingleloginlayer (); Console.log (Div1===DIV2);//Output True},false);

JavaScript Design Pattern Learning four--singleton 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.