Design Patterns in javascript: Singleton mode

Source: Internet
Author: User

Defined

The singleton pattern is that a class can only instantiate an object and provides a global access point to access it.

Generally in the implementation of the login box, or a global controller will use the singleton mode. In reality, there are window objects, thread pools, global caches, and so on.

Simple implementation

var function (name) {    this. Name = name;       This NULL  function(name) {    if(!  this. Instance) {        thisnew person (name);    }     return  This . instance;}
Kinds

The implementation of the singleton pattern is made up of many ways, and they also have different effects.

1. A single example implemented with a proxy

Sometimes, a proxy is used if you want a class to create an instance from a proxy, and you can use the normal method new for many instances.

 var  person = function   this . Name = name;};  var  Createperson = (function   () { var   instance;  return  function   if  (! return  new   person (name);     return   instance; }});

In the above code, if we were to create an instance, we would use Createperson to create it, and if it was like a normal object, it would be created with new.

2. Inertia single case

In fact, the simple singleton pattern introduced is the lazy Singleton, that is, the instance is created when needed. Instead of creating it from the beginning.

Design Patterns in javascript: 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.