In JavaScript, a single example pattern is one of the most basic and often used design patterns, and may inadvertently be used in a single case pattern.
This article will start with the most basic theory, the basic concept and implementation of the single case model, and finally use an example to describe the application of the single case pattern.
Theoretical basis
Concept
Singleton mode, as the name implies, is only one instance exists. A single example mode can guarantee that a class in a system has only one instance and that the instance is easy to access outside, thus it is convenient to control the number of instances and save the system resources. Single mode is the best solution if you want to have only one object for a class in the system.
Basic structure
The simplest example of a single pattern starts with an object literal, which organizes the associated properties and methods together.
var singleton = {
prop: ' Value ',
method:function () {
}
}
This form of a single case pattern, all members are public, can be accessed through singleton. The disadvantage is that there are some helper methods in the single case that do not want to be exposed to the user, and that if the user uses these methods and then maintains them later, some of the helper methods are removed, which can cause program errors.
How to avoid such mistakes?
A single case pattern containing private members
How to create a private member in the class, this by the need to close the package to implement, about the closure of knowledge, this article no longer repeat, we can Google.
The basic form is as follows:
var singleton = (function () {
var privatevar = "Private";
return {
prop: "Value",
method:function () {
console.log (Privatevar);}}
) ();
The first is a Privatevar anonymous function, in which an anonymous function declares a variable, returning an object assignment to a single Instance object singleton. The Privatevar variable cannot be accessed outside of an anonymous function, which is a private variable of a single Instance object and can only be accessed within the function or through the exposed method. This form is also a modular model.
Lazy instantiation
Either a direct literal or a private member of a single case pattern, both are created when the script is loaded, but sometimes the page may never be able to use this single Instance object, which can cause a waste of resources. In this case, the best way to deal with it is lazy loading, that is, when the need to really instantiate the Singleton object, how to achieve it?
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}
}
) ();
You first encapsulate the code that created the singleton object into the Init function, and then declare a private variable instance represents an instance of a singleton object, exposing a method getinstance to get the singleton object.
Calls are made by Singleton.getinstance (), and the single Instance object is actually created when the getinstance is invoked.
Applicable occasions
The single case pattern is the most commonly used design pattern in JS, and should be used as much as possible to use a single case pattern in terms of enhanced modularity and code organization. It can organize the relevant code together for easy maintenance, for large projects, each module lazy load can improve performance, hide implementation details, exposing the common API. Common libraries such as underscore,jquery can be understood as a single example of the application of the model.
Combined with actual combat
As we've already mentioned, the single case pattern is one of the most common design patterns, and we'll give you an example to illustrate
The following code mainly implements a simple date help class, implemented in a single example pattern:
Basic single case Pattern 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 implements the single example pattern through the literal amount of the object, and calls the method directly when used.
Lazy load implementation of single case mode
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 a single case pattern of lazy loading.
Let's look at a few more examples:
Implementation 1: The simplest object literal
var singleton = {
attr:1,
method:function () {return this.attr;}
}
var T1 = singleton;
var t2 = Singleton;
So obviously, T1 = = t2.
Very simple, and very useful, the disadvantage is that there is no encapsulation, all the property methods are exposed. The need for a few private variables to use the situation is powerless. Of course, there are some drawbacks to this issue.
Implement 2: Internal judgment of the constructor function
In fact, and the original JS implementation is somewhat similar, but will be the existence of the instance of the class has been placed inside the constructor.
function construct () {
//ensures that only single instance
if (construct.unique!== undefined) {return
construct.unique;
}
Other code
this.name = "NYF";
This.age= ";
" Construct.unique = this;
}
var T1 = new construct ();
var t2 = new construct ();
Then there are, T1 = = t2.
It is also very simple, it is simply to put forward a property to make a judgment, but this method also has no security, once I modified the unique properties of construct, then the single example mode is destroyed.
Implementation 3: Closure mode
For the big flexible brand of JS, any problem can find n kinds of answers, but let me weigh what is better, the following simple to give a few use closure to implement a single case mode, nothing more than the single example will create a cache.
var single = (function () {
var unique;
function construct () {
//... The code that generates the constructor for a single instance is
unique = new constuct ();
return unique;
}) ();
Whenever you speak var T1 = single; var t2 = single; is similar to the literal method of an object. But it is relatively safer and certainly not absolutely safe.
If you want to use the call single (), you only need to change the internal return to
return function () {return
unique;
The above method can also be used in the way of new (formalistic hurrying feet). Of course, this is just an example of a closure, you can also judge the existence of a single case in construct and so on. All kinds of ways in different situations can be selected.
Summary
The benefit of the singleton pattern is the organization of the Code, which encapsulates the associated properties and methods in an object that is not instantiated multiple times, making it easier to maintain and debug your code. Hides the implementation details, prevents errors from being modified, and prevents contamination of the global namespace. In addition, you can increase performance through lazy loading and reduce unnecessary memory consumption.