Singleton pattern in design pattern

The singleton pattern is a common pattern in the front-end design pattern. The singleton pattern is a creational pattern that ensures that a class has only one instance and provides a global access point. In front-end development, singleton mode is usually used to manage global state, configuration information, cache data, etc. The singleton mode can avoid the abuse of global variables and improve the maintainability and scalability of the code. There are many ways to implement the singleton pattern, the most common way is to use closures to implement private properties and methods.

For example, Vuex in Vue is developed using the singleton mode

Sample code one

In Vuex, a class called Store is used to create a global state manager, and this class is a singleton. When creating a Store instance, if there is already a Store instance, then return the instance directly, otherwise create a new Store instance and return it. In this way, it can be ensured that there is only one Store instance in the entire application, so as to realize the management and sharing of the global state

In Vue, the singleton pattern can be used to create a global state manager to share data among different components. Here is an example of the singleton pattern used in Vue:

// store.js
import {
    
     reactive } from 'vue';

let store = null;

export function useStore() {
    
    
  if (!store) {
    
    
    store = reactive({
    
    
      count: 0
    });
  }
  return store;
}


storeIn this example a global state manager called is created and reactiveconverted to a reactive object using We then storeencapsulated the object useStorein a function named , and used the singleton pattern to ensure that only one storeobject was created. Each useStoretime the function is called, if storethe object does not exist, a new storeobject is created and assigned to storethe variable. Otherwise, return the existing store object directly.
When using an object in a component store, you only need to call useStorea function to get the global storeobject and use it in the template store.countto access countproperties. For example:

<template>
  <div>
    <button @click="increment">Increment</button>
    <div>Count: {
    
    {
    
     store.count }}</div>
  </div>
</template>

<script setup>
import {
    
     useStore } from './store.js';

const store = useStore();

function increment() {
    
    
  store.count++;
}
</script>

Sample code two

var Singleton = (function() {
    
    
  var instance;
  function createInstance() {
    
    
    var object = {
    
    
      name: 'Singleton Object',
      sayHello: function() {
    
    
        console.log('Hello, I am the instance.');
      }
    };
    return object;
  }
  return {
    
    
    getInstance: function() {
    
    
      if (!instance) {
    
    
        instance = createInstance();
      }
      return instance;
    }
  };
})();

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

console.log(instance1 === instance2); // 输出:true
instance1.sayHello(); // 输出:Hello, I am the instance.

In createInstancethe method, a new object is created and the name and method are added to the object. Finally, we return this object.
When using the singleton pattern, we call getInstancemethods to get the singleton object. In getInstancethe method, we use the if statement to determine whether the singleton object has been created, and if not, call createInstancethe method to create the singleton object. In the end, we end up with two identical singleton objects, and they are the same instance. We also call methods on the singleton object sayHello, which outputs a greeting.

As you can see, the singleton pattern can use any type of object to represent a singleton object, including primitive types, objects, functions, and so on. When implementing the singleton pattern, we can define the properties and methods of the singleton object according to actual needs, so as to achieve richer and more flexible functions.

Guess you like

Origin blog.csdn.net/weixin_43811753/article/details/130166791