Home > Article > Web Front-end > Explanation of Singleton Design Model for JavaScript Programming_Basic Knowledge
In Javascript, the singleton pattern is one of the most basic and frequently used design patterns. You may use the singleton pattern inadvertently.
This article will start with the most basic theory, describe the basic concepts and implementation of the singleton pattern, and finally use an example to describe the application of the singleton pattern.
Theoretical basis
Concept
Singleton mode, as the name implies, means that only one instance exists. The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to access from the outside world, thereby facilitating control of the number of instances and saving system resources. If you want only one object of a certain class to exist in the system, the singleton pattern is the best solution.
Basic structure
The simplest singleton pattern starts with an object literal, which organizes related properties 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 of this is that there are some auxiliary methods in the singleton that are not expected to be exposed to users. If the user uses these methods, and then some auxiliary methods are deleted during subsequent maintenance, this will cause program errors.
How to avoid such mistakes?
Singleton pattern with private members
How to create private members in a class? This is achieved by requiring closures. Regarding the knowledge of closures, this article will not go into details. You can Google it yourself.
The basic form is as follows:
var singleton = (function () { var privateVar = "private"; return { prop: "value", method: function () { console.log(privateVar); } } })();
The first is a self-executing anonymous function. In the anonymous function, a variable privateVar is declared and an object is returned and assigned to the singleton object. The privateVar variable cannot be accessed outside the anonymous function. It is the private variable of the singleton object. This private variable can only be accessed inside the function or through exposed methods. This form is also called the module pattern.
Lazy instantiation
Whether it is a direct literal or a private member singleton mode, both are singletons that are created when the script is loaded. However, sometimes, the page may never use this singleton object, which will causing a waste of resources. For this situation, the best way to deal with it is lazy loading, which means that the singleton object is not actually instantiated until needed. How to achieve this?
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 into the init function, then declare a private variable instance to represent the instance of the singleton object, and expose a method getInstance to obtain the singleton object.
When calling, it is called through singleton.getInstance(). The singleton object is actually created when getInstance is called.
Applicable occasions
The singleton pattern is the most commonly used design pattern in JS. From the aspects of enhancing modularity and code organization, the singleton pattern should be used as much as possible. It can organize related codes together for easy maintenance. For large projects, lazy loading of each module can improve performance, hide implementation details, and expose commonly used APIs. Common class libraries such as underscore and jQuery can be understood as singleton mode applications.
Combined with actual combat
As mentioned before, the singleton pattern is one of the most commonly used design patterns. Let’s give an example to illustrate,
The following code mainly implements a simple date helper class, implemented through singleton mode:
Basic singleton pattern structure
var dateTimeHelper = { now: function () { return new Date(); }, format: function (date) { return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(); } }; console.log(dateTimeHelper.now());<br />
This code implements the singleton mode through object literals, and you can directly call the method when using it.
Lazy loading implements singleton pattern
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 lazy loading singleton pattern.
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.
It is very simple and very easy to use. The disadvantage is that there is no encapsulation and all attribute methods are exposed. For some situations where private variables need to be used, it seems to be insufficient. Of course, there are also certain disadvantages when it comes to this.
Implementation 2: Constructor internal judgment
In fact, it is somewhat similar to the original JS implementation, except that the judgment of whether an instance of the class already exists is placed inside the constructor.
function Construct(){ // 确保只有单例 if( Construct.unique !== undefined ){ return Construct.unique; } // 其他代码 this.name = "NYF"; this.age="24"; Construct.unique = this; } var t1 = new Construct() ; var t2 = new Construct() ;
那么也有的, t1 === t2 。
也是非常简单,无非就是提出一个属性来做判断,但是该方式也没有安全性,一旦我在外部修改了Construct的unique属性,那么单例模式也就被破坏了。
实现3 : 闭包方式
对于大着 灵活 牌子的JS来说,任何问题都能找到 n 种答案,只不过让我自己去掂量孰优孰劣而已,下面就简单的举几个使用闭包实现单例模式的方法,无非也就是将创建了的单例缓存而已。
var single = (function(){ var unique; function Construct(){ // ... 生成单例的构造函数的代码 } unique = new Constuct(); return unique; })();
只要 每次讲 var t1 = single; var t2 = single;即可。 与对象字面量方式类似。不过相对而言更安全一点,当然也不是绝对安全。
如果希望会用调用 single() 方式来使用,那么也只需要将内部的 return 改为
return function(){ return unique; }
以上方式也可以使用 new 的方式来进行(形式主义的赶脚)。当然这边只是给了闭包的一种例子而已,也可以在 Construct 中判断单例是否存在 等等。 各种方式在各个不同情况做好选着即可。
总结
单例模式的好处在于对代码的组织作用,将相关的属性和方法封装在一个不会被多次实例化的对象中,让代码的维护和调试更加轻松。隐藏了实现细节,可以防止被错误修改,还防止了全局命名空间的污染。另外可以通过惰性加载提高性能,减少不必要的内存消耗。