


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 中判断单例是否存在 等等。 各种方式在各个不同情况做好选着即可。
总结
单例模式的好处在于对代码的组织作用,将相关的属性和方法封装在一个不会被多次实例化的对象中,让代码的维护和调试更加轻松。隐藏了实现细节,可以防止被错误修改,还防止了全局命名空间的污染。另外可以通过惰性加载提高性能,减少不必要的内存消耗。

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)