Home>Article>Web Front-end> JavaScript design pattern singleton pattern
Preface
In the development process of JavaScript, pioneers have summarized many solutions to specific problems from practice. Simply put, a design pattern is a concise and elegant solution to a specific problem on a certain occasion
In the following period, I will record various common design patterns in JavaScript. Maybe you are already familiar with it, maybe you have used it on a daily basis, but you are not particularly familiar with its concept, or maybe you only have some vague concepts about it. Then, I believe this series will definitely bring you some gains
Before understanding these common patterns, by default you have at least mastered
this
Closure
Higher-order functions
Prototypes and prototype chains
Understanding them will help you understand a pattern more clearly. Of course, maybe the things I have recorded in this regard can give you some helpPortal
If there are any flaws or mistakes in the article, please also read it. Thank you in advance for your advice
Now, let us start with it--single case mode
Concept
As the name suggests, there is only one instance.
Definition: Ensure that a class has only one instance and provide a global access point to access it
Seeing such a definition, do you have any thoughts in your mind? What about the concept of global variables? It is undeniable that global variables conform to the concept of singleton pattern. However, we usually do not and should not use it as a singleton for the following two reasons:
Global naming pollution
Not easy to maintain, easy to be overwritten
Before ES6, we usually used a constructor to simulate a class. Now we can also directly use the class keyword to create a class. , although its essence is also a prototype
To ensure that a class has only one instance, we need to provide a variable to mark whether an instance has been created for a class. Therefore, the core of the singleton mode is:Ensure that there is only one instance and provide global access
Around this core, we basically understand the implementation of the singleton mode
Implementation
Basic version
According to the definition of singleton pattern, we can simply implement it in the following way
var Singleton = function(name){ this.name = name } Singleton.instance = null // 初始化一个变量Singleton.getInstance = function(name) {// 判断这个变量是否已经被赋值,如果没有就使之为构造函数的实例化对象// 如果已经被赋值了就直接返回 if(!this.instance) { this.instance = new Singleton(name) } return this.instance } var a = Singleton.getInstance('Tadpole') var b = Singleton.getInstance('Amy') a === b // true
The above code clearly reflects the definition of the singleton pattern. Only one instance is initialized through an intermediate variable, so in the end a and b are completely equal
We can also use the class keyword of ES6 to achieve it
class Singleton { constructor(name){ this.name = name this.instance = null } // 提供一个接口对类进行实例化 static getInstance(name) { if(!this.instance) { this.instance = new Singleton(name) } return this.instance } }
It is not difficult to find that ES6 The implementation method is basically the same as our implementation through the constructor.
There are problems:
is not transparent enough, we need to constrain the calling method of class instantiation
The coupling is too high, and coupling functional business codes together is not conducive to later maintenance
Constructor
Let us make a simple modification to the above method
// 将变量直接挂在构造函数上面,最终将其返回 function Singleton(name) { if(typeof Singleton.instance === 'object'){ return Singleton.instance } this.name = name return Singleton.instance = this } // 正常创建实例 var a = new Singleton('Tadpole') var b = new Singleton('Amy')
Solve the problem that the basic version of the class is not transparent enough. You can use the new keyword to initialize the instance, but there are also new The problem
Determine the Single.instance type to return, you may not get the expected results
The coupling is too high
This method can also be implemented through ES6 method
// 将 constructor 改写为单例模式的构造器 class Singleton { constructor(name) { this.name = name if(!Singleton.instance) { Singleton.instance = this } return Singleton.instance } }
Closure
Through the definition of singleton mode, you want to ensure that there is only one instance and that global access can be provided. Then, closures can definitely achieve such needs
var Singleton = (function () { var SingleClass = function () {}; var instance; return function () { if (!instance) { instance = new SingleClass() // 如果不存在 则new一个 } return instance; } })()
Through the characteristics of closures, a variable is saved and eventually returned, providing global access
Similarly, the above code still does not work Solve the problem of coupling
Let us carefully observe this piece of code. If we extract the constructor part to the outside, will the separation of functions be achieved?
Agent implementation
Modify the above code
function Singleton(name) { this.name = name } var proxySingle = (function(){ var instance return function(name) { if(!instance) { instance = new Singleton(name) } return instance } })()
将创建函数的步骤从函数中提取出来,把负责管理单例的逻辑移到了代理类 proxySingle 中。这样做的目的就是将 Singleton 这个类变成一个普通的类,我们就可以在其中单独编写一些业务逻辑,达到了逻辑分离的效果
我们现在已经达到了逻辑分离的效果,并且也不 透明 了。但是,这个负责代理的类是否已经完全符合我们的要求呢,答案是否定的。设想一下,如果我们的构造函数有多个参数,我们是不是也应该在代理类中体现出来呢
那么,有没有更通用一些的实现方式呢
通用惰性单例
在前面的几个回合,我们已经基本完成了单例模式的创建。现在,我们需要寻求一种更通用的方式解决之前留下来的问题
试想一下,如果我们将函数作为一个参数呢
// 将函数作为一个参数传递 var Singleton = function(fn) { var instance return function() { // 通过apply的方式收集参数并执行传入的参数将结果返回 return instance || (instance = fn.apply(this, arguments)) } }
这种方式最大的优点就是相当于缓存了我们想要的结果,并且在我们需要的时候才去调用它,符合封装的单一职责
应用
前面有说过,所有的模式都是从实践中总结而来,下面就让我们来看看它在实际开发中都有哪些应用吧
通过单例模式的定义我们不难想出它在实际开发中的用途,比如:全局遮罩层
一个全局的遮罩层我们不可能每一次调用的时候都去创建它,最好的方式就是让它只创建一次,之后用一个变量将它保存起来,再次调用的时候直接返回结果即可
单例模式就很符合我们这样的需求
// 模拟一个遮罩层var createDiv = function () { var div = document.createElement('div') div.style.width = '100vw' div.style.height = '100vh' div.style.backgroundColor = 'red' document.body.appendChild(div) return div }// 创建出这个元素var createSingleLayer = Singleton(createDiv)document.getElementById('btn').onclick = function () { // 只有在调用的时候才展示 var divLayer = createSingleLayer() }
当然,在实际应用中还是有很多适用场景的,比如登录框,还有我们可能会使用到的 Vux 之类的状态管理工具,它们实际上都是契合单例模式的
后记
单例模式是一种简单而又实用的模式,通过创建对象和管理单例的两个方法,我们就可以创造出很多实用且优雅的应用。当然,它也有自身的缺点,比如只有一个实例~
合理使用才能发挥出它的最大威力
最后,推荐一波前端学习历程,感兴趣的小伙伴可以 点击这里 ,也可以扫描下方二维码关注我的微信公众号,查看往期更多内容,欢迎 star 关注
推荐教程:《JS教程》
The above is the detailed content of JavaScript design pattern singleton pattern. For more information, please follow other related articles on the PHP Chinese website!