Examples of JavaScript programming: design templates and javascript programming

Source: Internet
Author: User

Examples of JavaScript programming: design templates and javascript programming

In Javascript, the singleton mode is the most basic and frequently used design mode, and may be inadvertently used in the singleton mode.
This article describes the basic concepts and implementations of the singleton mode from the basic theory, and uses an example to describe the application of Singleton mode.

Theoretical Basis

Concept

Singleton mode, as its name implies, only one instance exists. The Singleton mode ensures that there is only one instance in a class in the system and the instance is easy to access, so as to conveniently control the number of instances and save system resources. If you want to have only one class object in the system, the singleton mode is the best solution.

Basic Structure

The simplest Singleton mode starts with an object literal, which organizes associated attributes and methods together.

var singleton = {  prop:"value",  method:function(){  }}

In this form of singleton mode, all members are public and can be accessed through singleton. The disadvantage is that some auxiliary methods in the singleton do not want to be exposed to the user. If the user uses these methods, some auxiliary methods will be deleted during subsequent maintenance, this will cause program errors.
How can we avoid such errors?

Singleton mode with Private Members

How can we create private members in a class? This is implemented by using closures. We will not go into details about closures in this article. You can Google them on your own.
The basic format is as follows:

var singleton = (function () {      var privateVar = "private";      return {        prop: "value",        method: function () {          console.log(privateVar);        }      }    })();

The first is a self-executed anonymous function. In the anonymous function, a variable privateVar is declared, and an object is returned with a value assigned to singleton. The privateVar variable cannot be accessed outside the anonymous function. It is the private variable of the singleton object and can only be accessed inside the function or through exposed methods. This form has become a module model.

Inert instantiation

Whether it is the singleton mode of the direct literal or private member, both are the singleton created when the script is loaded. However, sometimes the page may never use this singleton object, this will cause a waste of resources. In this case, the best way to deal with it is to load it with inertia. That is to say, how can this singleton object be instantiated only when necessary?

var singleton = (function () {      function init() {        var privateVar = "private";        return {          prop: "value",          method: function () {            console.log(privateVar);          }        }      }      var instance = null;      return {        getInstance: function () {          if (!instance) {            instance = init();          }          return instance;        }      }    })();

First, encapsulate the code for creating a singleton object in the init function, declare a private variable instance to indicate the instance of the singleton object, and publish a method getInstance to obtain the singleton object.
Singleton. getInstance () is used for calling. A singleton object is created only when getInstance is called.

Applicable scenarios

The Singleton mode is the most commonly used design mode in JS. In terms of enhanced modularity and code organization, we should try our best to use the singleton mode. It organizes the relevant code to facilitate maintenance. For large projects, the inert loading of each module can improve performance, hide implementation details, and expose common APIs. Common class libraries such as underscore and jQuery can be understood as single-instance applications.

Combined with practice

As mentioned above, the singleton mode is one of the most common design patterns. Let's give an example to illustrate it,
The following code implements a simple date help class through the singleton mode:

Basic Singleton mode structure

var dateTimeHelper = {      now: function () {        return new Date();      },      format: function (date) {        return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();      }    }; console.log(dateTimeHelper.now());

This Code uses the object literal to implement the singleton mode. You can directly call the method when using it.

Implement the singleton mode by using inert Loading

 var dateTimeHelper = (function () {      function init() {        return {          now: function () {            return new Date();          },          format: function (date) {            return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();          }        }      }      var instance = null;      return {        getInstance: function () {          if (!instance) {            instance = init();          }          return instance;        }      }    })(); console.log(dateTimeHelper.getInstance().now())

This is the single-instance mode of inert loading.

Here are some examples:
Implementation 1: Simplest object literal

var singleton = {    attr : 1,    method : function(){ return this.attr; }  }var t1 = singleton ;var t2 = singleton ;

Obviously, t1 = t2.

It is very easy to use and has no encapsulation. All attribute methods are exposed. For some situations where private variables need to be used, it seems insufficient. Of course, this problem also has some drawbacks.

Implementation 2: Internal judgment of the constructor

In fact, it is a bit similar to the original JS implementation, but it puts the judgment on whether the class already exists into the constructor.

Function Construct () {// ensure that only the singleton if (Construct. unique! = Undefined) {return Construct. unique;} // other code this. name = "NYF"; this. age = "24"; Construct. unique = this;} var t1 = new Construct (); var t2 = new Construct ();

So there are also, t1 = t2.

It is also very simple. It is nothing more than proposing an attribute for judgment, but this method is not secure. Once I modify the unique attribute of Construct outside, the singleton mode will be destroyed.

Implementation 3: Closure

For JS with a big brand of flexibility, I can find n answers to any questions, but I just want to handle the advantages and disadvantages of others, the following is a simple example of how to use closures to implement the singleton mode, that is, to cache the created Singleton.

Var single = (function () {var unique; function Construct (){//... code for generating the constructor for a single instance} unique = new Constuct (); return unique ;})();

You only need to talk about var t1 = single; var t2 = single; each time. Similar to object literal. But it is relatively safer, and of course it is not absolutely safe.

If you want to use the single () method, you only need to change the internal return

  return function(){    return unique;  } 

The above method can also be implemented using the new method (the catch-up of formalism ). Of course, this is just an example of closure. You can also determine whether a singleton exists in Construct. Various methods can be selected in different situations.


Summary

The benefit of the singleton mode is the Code Organization function. It encapsulates relevant attributes and methods in an object that will not be instantiated multiple times, making code maintenance and debugging easier. The implementation details are hidden to prevent incorrect modification and global namespace contamination. In addition, the performance can be improved through inert loading to reduce unnecessary memory consumption.

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.