JS Learning 16-day----Single-case mode

Source: Internet
Author: User

Single-Case mode

To tell the truth , today originally did not want to write a blog , but after thinking , rather than look at the film , rather than typing ( gun ), or write a little , not much to write the simplest , do not look simple , But it's very common .

Found a good thing today is called Kiwi Encyclopedia I saw it in there. A little introduction to the singleton pattern Because this cock is not very fond of the concept of transcription. But the encyclopedia says it's good. copy it for you. :

When you apply a singleton pattern , the class that generates the singleton must guarantee that only one instance exists , and many times the entire system needs only one global object . is conducive to the coordination of the overall system of behavior . For example, in the entire system configuration file , configuration data has one singleton object set for unified read and modify , when other objects need to configure data, they also unify the singleton object to get the configuration data. , This simplifies configuration management in complex environments .

The idea of a single case model:A class can return a reference to an object(and always the same one .)and a way to get to the force.(Static Methods,typically usedgetinstancename).So when we call this method,,returns the reference if the class holds a reference that is not empty,Otherwise, create an instance of the class,and assigns the instance reference to the same reference that the class holds and returns.The constructor of the class is also defined as a private,avoid other functions using this constructor to instantiate an object,only the static method of the class is used to get the unique instance of the class.

For JS , great flexibility makes it possible to implement singleton patterns in a variety of ways , using closures to simulate private data , According to their ideas can get ( do not know what the closure is the thing to the Encyclopedia ):

var single= (function () {

var unique;

function getinstance () {

if (unique==undefined) {

Unique=new Construct ();


return unique;


function Construct () {

code that generates the constructor in the But


return {




Analysis : Unique is a reference to the return object , and getinstance is the static method to obtain the instance . Construct is the constructor that creates the instance . can be done by Single . getinstance () to get to the singleton , and each call gets to the same singleton . This is what the singleton pattern achieves .

JS language style is quite flexible , The above realization of the way is obviously cumbersome , since JS has its own advantages , Then we can use The advantages of JS to achieve a singleton mode .

Implementation 1: The simplest object literal

var singleton={


Method:function () {return this.attr;}


var T1=singleton;

var T2=singleton;

alert (T1==T2);//true

Analysis : simple and easy to use, The disadvantage is that there is no object-oriented encapsulation of a bit , all the property methods are exposed . for some cases where private variables need to be used, it can be very weak. . in the case of This There are some drawbacks to the problem . .

Implementation 2: constructor internal judgment

function Construct () {

ensure that only a single case

if (construct.unique!==undefined) {

return construct.unique;


other Code

This.name= "Syx";

This.age= "22";



var t1=new Construct ();

var t2=new Construct ();

alert (t1==t2);/ / true

Analysis : is also simple , nothing more than to put forward a property to make judgments , But there is no security in this way , Once I have modified the unique Properties of the Construct externally , the singleton mode destroys the .

Implementation 3: closure Mode

For the flexible banner of JS to hand , any problem can find the answer to n , but let me weigh the pros and cons , Here are simply a few ways to implement a singleton pattern using closures , which is nothing more than a singleton cache that will be created .

var single= (function () {

var unique;

function Construct () {

code to generate a single-instance constructor


Unique=new Construct ();

return unique;


As long as the var t1=single;var t2=single each time; can be . similar to object literal . but relatively safer . , Of Course it's not absolute. .

If you want to use the call single () , then you only need to change the internal return to : return function () {

return unique;


The above method can also be done using the new method . of course, that's when we give a case that must be reported . , can also be in Construct whether a single case exists, etc. . various ways to choose in different situations .


Singleton mode is relatively simple in each major mode , but singleton mode is the most common and useful . in the JS Is particularly prominent in ( Each object literal can be considered a singleton ).

Remember , the strict need for only one instance object class ( although JS does not have the concept of Class ), then consider using a singleton .

Using the data cache to store the singleton , as a way to determine whether a single case has been generated , is the primary implementation of the Singleton mode .

Extend the concept of closures :

What is a closure package?
The "official" explanation is that the so-called "closure" refers to an expression (usually a function) that has many variables and an environment in which these variables are bound, and therefore these variables are also part of the expression.
It is believed that very few people can read this sentence directly because he describes it as too academic. I want to use how toJavascriptcreates a closure package that tells you what a closure is, because it is very difficult to understand the definition of closures directly as the process of skipping closures is created. Look at the following code:
function A () {
var i=0;
Function B () {
alert (++i);
return b;
var C = A ();
C ();
There are two features of this code:
1, FunctionsbNesting in Functionsainternal;
2, Functionsareturn functionb.
So after the executionvar c=a ()after the variableCis actually pointing to the functionb, and then executeC ()A window will pop up to showIthe value(first time for1). This code actually creates a closure, why? Because the functionaoutside of the variableCreferencing a functionafunctions within theb, that is to say:
When the functionathe intrinsic functionbis functionaA closure is created when a variable is referenced outside the

What is the effect of closures?
In short, the function of closures is toaafter execution and return, the closure makesJavascriptthe garbage collection mechanismGCwill not take backaThe resources that are occupied becauseathe intrinsic functionbthe execution needs to depend onavariables in the. This is a very straightforward description of the effect of closures, unprofessional and not rigorous, but the general meaning is that, understanding closures need a gradual process.
In the example above, the existence of a closure makes the functionawhen returned,ain theIis always present so that each executionC (),IIt's all self-added .1afterAlertoutIthe value.
So let's imagine another situation, ifareturned is not a functionb, the situation is completely different. Becauseawhen you 're done,bnot be returned toathe outside world, just beingareferenced, and at this timeait will only bebreference, so the functionaand thebquoting each other but not being disturbed by the outside world .(be quoted by the outside world), the functionaand thebwill beGCRecycling.

Application of closures
1, the security of variables within the protection function. In the first example, the functionainIonly Functionsbcan be accessed, and cannot be accessed by other means, thus protecting theIthe security.
2, maintaining a variable in memory. As in the preceding example, due to closures, the functionainIis always present in memory, so each executionC (), will giveIself-added1.
The above two points are the most basic application scenarios for closures, and many of the classic cases originate from this.

Think I write to you a little bit of help , give a praise Oh , ( づ ̄3 ̄) づ╭?~

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JS Learning 16-day----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.