JavaScript Design patterns and Development Practices-4th chapter-Singleton mode

Source: Internet
Author: User

Definition of a singleton pattern: guarantees that a class has only one instance and provides a global access point to access it

Implement Singleton mode: Save an instance of a singleton pattern class, each time a new instance is created, there are no instances saved, and some return to the original instance.

Use a proxy to implement a singleton pattern: separate the "things" and "judge whether Singleton" codes that are actually done in the singleton mode (actually the same purpose as the following Getsingle, which is based on the implementation of the "class")

1 varProxysingletoncreatediv = (function(){2 3     varinstance;4     return function(HTML) {5         if( !instance) {6Instance =Newcreatediv (HTML);7             returninstance;8         }9         returninstance;Ten     } One  A})();

How to better use global variables:

    • Using namespaces
    • Encapsulating private variables with closures

General Lazy Singleton: the duties of "create instance object" and "manage a singleton" are placed in two methods respectively, which focus on the management of the Singleton Method-getsingle ().

1 varGetsingle =function(FN) {2     varresult;3     //The closure is formed here .4     return function(){5         //the contents of the parentheses do two things: Create an instance and store the instance in a closed package6         returnResult | | (Result = Fn.apply ( This, arguments));7     }8};

JavaScript Design patterns and Development Practices-4th chapter-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.