A concept,

A pattern that guarantees only one instance of a class and provides a global access point to access it is called a singleton pattern.

Singleton pattern is relatively easy to understand and use in design pattern, and it is also a frequent interview question because of its wide range of application scenarios.

Second, implementation ideas

Now let’s look at the implementation of the singleton pattern rather than the application scenario, and consider the following question: How can we ensure that there is only one instance of a class? In general, when we create a class (which is essentially a constructor), we can call the constructor with the new keyword to generate as many instance objects as we want. Like this:

class SingleDog {
    show() {
        console.log('I'm a singleton')}}const s1 = new SingleDog()
const s2 = new SingleDog()

// false
s1 === s2
Copy the code

We first new s1, then we new s2, and obviously s1 and S2 have nothing to do with each other, they are independent objects, each taking up a piece of memory. What the singleton pattern wants to do is, no matter how many times we try to create it, it just gives you back the only instance of the one you created the first time. To do this, you need the constructor to have the ability to determine whether it has created an instance. We now write this logic as a static method (which can also be written directly into the body of the constructor) :

3. Simple demo

Class SingleDog {show() {console.log(' I am a singleton ')} static getInstance() {if (! Singledog.instance = new SingleDog()} // If the SingleDog instance already exists, Return singledog.instance}} const s1 = singledog.getInstance () const s2 = singledog.getinstance () // true  s2Copy the code

In addition to the above implementation, closures can also be used to implement:

Singledog.getinstance = (function() {// define a free variable instance, Let instance = null return function() {let instance = null return function() { Instance = new SingleDog()} return instance}})()Copy the code

Four, extension,

1. The singleton mode in Vuex

Vuex uses a single state tree that contains all application-level states in a single object. At this point it exists as a “unique data source (SSOT)”. This also means that each app will contain only one Store instance. A single state tree allows us to directly locate any particular state fragment and easily take a snapshot of the entire current application state during debugging. — Vuex official document

In Vue, components are independent of each other, and the most common way to communicate between components is props (limited to communication between parent and child components). A little more complex (such as communication between siblings) can be solved by implementing simple event listener functions ourselves.

However, when there are many components, the relationship between components is complex, and the nesting level is deep, this primitive communication method can make our logic complicated and difficult to maintain. It is best to pull out the shared data globally so that components can access the data according to certain rules and ensure that the state changes in a predictable way. Here comes Vuex, the only source of shared data, the Store.

How does Vuex ensure Store uniqueness

Let’s start by looking at how to introduce Vuex into a project:

New Vue({el: '#app', store}) new Vue({el: '#app', store})Copy the code

We installed the Vuex plug-in by calling the vue.use () method. The Vuex plug-in is an object that internally implements a install method, which is called when the plug-in is installed to inject the Store into the Vue instance. That is, every time you install, you try to inject a Store into the Vue instance.

In the install method, there is a very similar logic to getInstance:

Let Vue // let Vue is the same as instance... Export function install (_Vue) {if (Vue &&_vue === Vue) {if (Vue &&_vue === Vue) {if (Vue &&_vue === Vue) {if (process.env.NODE_ENV ! == 'production') { console.error( '[vuex] already installed. Vue.use(Vuex) should be called only once.' ) } return } // Vue = _Vue // Write Vuex initialization logic to Vue hook function applyMixin(Vue)}Copy the code

The above is Vuex source singleton mode implementation method, routine can be said to be the same as our getInstance. In this way, it is guaranteed that a Vue instance (i.e. a Vue application) will only be installed once for the Vuex plug-in, so each Vue instance will have only one global Store.