Singleton mode in TypeScript

Sync link: https://www.shanejix.com/TypeScript Singleton mode in/

Singleton pattern (singleton): a class has and instantiates only one instance object

More specifically:

If a class provides only one object instance and a unique method or property that can access the object,

This ensures the uniqueness of the object

So why not declare an object directly, but instantiate an object through a class?

Obviously, it makes maximum use of the idea of object-oriented: it is more encapsulated and easier to expand

scene

When to use singleton mode? Of course, it is considered from the important characteristics of the singleton pattern itself: uniqueness

Unique: there is only one independent. If this feature is met, the singleton mode can be considered.

For example:

Scenario 1: client storage

localStore/sessionStory => The same source policy, the same protocol, the same domain name and the same port share the same data => Singleton mode

Scenario 2: global status management

Global state store => SPA Shared global properties and methods (unique instance objects) => Singleton mode( react-redux , vuex Etc.)

Of course, there are many scenes ~ such as simulating an earth and the solar system

pattern

How to implement the singleton pattern in typescript? Take the client storage in scenario 1 as an example:

Step 1: privatize the constructor

class LocalStorageLayz {
  // Privatization constructor
  private constructor() {}
}

Step 2: provide external accessible methods, and call this method to get the unique object instance of the current class

class LocalStorageLayz {
  // The static property references a unique instance object of the localstotrace class
  static localStorage: LocalStorageLayz;

  // Privatization constructor
  private constructor() {}

  // Provides an externally accessible static method
  public static getInstance() {
    if (!this.localStorage) {
      this.localStorage = new LocalStorageLayz();
    }

    return this.localStorage;
  }

  // Example method
  public getItem(key: string) {
    let val = localStorage.getItem(key);
    return val !== null ? JSON.parse(val) : null;
  }

  // Example method
  public setItem(key: string, val: any) {
    localStorage.setItem(key, JSON.stringify(val));
  }
}

Step 3: externally call the method provided in step 2 to get a unique instance

const instanceLayz = LocalStorageLayz.getInstance();

instanceLayz.setItem("instanceLayz", { "1": 1, "2": 3 });

let val = instanceLayz.getItem("instanceLayz");

console.log("inatanceLayz", val);

In the second step, you can directly reference the instance object through the externally provided static properties, or you can initialize the static properties through the externally provided static methods. As follows:

class LocalStorage {
  // The static property references a unique instance object of the localstotrace class
  static localStorage: LocalStorage = new LocalStorage();

  // Privatization constructor
  private constructor() {}

  // Example method
  public getItem(key: string) {
    let val = localStorage.getItem(key);
    return val !== null ? JSON.parse(val) : null;
  }

  // Example method
  public setItem(key: string, val: any) {
    localStorage.setItem(key, JSON.stringify(val));
  }
}

The difference is that the opportunity to mount a unique instance can be manually controlled through static methods, while the static attribute will be mounted on the static attribute when the class is loaded

const instance = LocalStorage.localStorage;
instance.setItem("instance", { "3": 3, "4": 4 });
const value = instance.getItem("instance");
console.log("instance", value);

summary

The specific logic of realizing singleton pattern through static members (static methods / static attributes) in typescript is simply realized: firstly, the important characteristics of singleton pattern: single instance; Then how to ensure that a class has and only has one instance?

  • Provide a static attribute or static method externally;
  • Instantiate the singleton when the class is mounted or manually instantiate the singleton through the provided static method

Maybe you wonder why the single example is not directly put on the prototype? But on the static members of the class? The premise here is to know the static members of the class and the prototype mechanism in JavaScript!

references

Author: shanejix
source: https://www.shanejix.com/TypeScript Singleton mode in/
Copyright: this work adopts "Signature - non commercial use - share 4.0 international in the same way" License under the license agreement.
Statement: please indicate the source for reprint!

Posted on Fri, 03 Dec 2021 11:17:33 -0500 by e_00_3