Singleton (Singleton pattern)

Singleton is a creation pattern that provides a way to get objects that are guaranteed to be unique within a certain scope.

Intent: Ensure that a class has only one instance and provide a global access point to access it.

In fact, the singleton mode is not obvious in the front end for the following reasons:

  1. The front-end code itself runs on a stand-alone machine, and any variables created are naturally distributed without worrying about affecting another user.
  2. The back-end code is one-to-many, and it is important to distinguish which resources are shared between requests and which are unique within requests.

And when we talk about singletons, we’re implying a scope, we’re talking about singletons within a certain scope, whether it’s in a context, whether it’s in a room, whether it’s in a process, whether it’s in a thread, the scope varies from scenario to scenario.

For example,

If you don’t understand the above description, it doesn’t matter. Design patterns need to be used in daily work. Examples will help you understand better.

Shared items in multiplayer games

Those of you who have played the game know that the public goods we use in each game are unique in the current room, but not in the game room. Therefore, there must be different categories to describe these public goods. How can we get the public goods in each game to ensure that they are unique in the current game?

Redux data flow

In fact, the front-end Redux data stream itself is a singleton pattern. In one application, the data is unique, but it can be used by different UIs, and even a table component can be displayed in two different places, such as in full screen mode, but the data is still one, we don’t need to display the table in full screen. Let it make another fetch request, and share a piece of data with the original table.

Database connection pool

Each SQL query depends on the database connection pool. If you create a database connection pool for each query, the connection will be set up much slower than the SQL query. So how do you design the database connection pool retrieval method?

Intention to explain

The intent of the singleton pattern is simple, almost literal:

Intent: Ensure that a class has only one instance and provide a global access point to access it.

For a shared item in a multiplayer game, such as a pot, to be unique within a game, provide a way to access a unique instance.

The CONNECT decorator for Redux data flows is one such design for global access points.

The database connection pool can be pre-initialized and provided with a unique instance via a fixed API.

chart

A Singleton is an interface to the Singleton pattern, and customers can access instances only through its defined instance() to guarantee singletons.

The code example

The following example is written in typescript.

class Ball {
  private _instance = undefined

  The constructor is declared private to prevent new Ball() behavior
  private constructor() {}

  public static instance = () = > {
    if (this._instance === undefined) {
      this._instance = new Ball()
    }

    return this._instance
  }
}

/ / use
const ball = Ball.getInstance()
Copy the code

If you think about it, why does this example write a singleton as a static method instead of a global variable? In fact, global variables can also solve the problem, but since they pollute the world, it is best to solve it in a modular way. The above example is a good encapsulation method.

Of course, this is only the simplest example, but there are actually several more singleton patterns:

The hungry type

When initialized, an instance is generated so that it can be retrieved directly when called.

LanHanShi

That’s what the code example says, instantiate on demand, that is, instantiate as you call it.

Note that on demand is not always a good thing. If New is expensive and instantiated on demand, it may leave the risk of system exceptions to random trigger times, making it difficult to detect bugs and affecting system time on the first instantiation.

For JAVA, singletons also need to be considered for concurrency, with solutions such as double detection, static inner classes, and enumerations, which are not detailed here.

disadvantages

The problems with the singleton pattern are:

  • Not very object-oriented friendly. Not friendly to encapsulation, inheritance, and polymorphic support.
  • It is not helpful to tease out dependencies between classes. After all, singletons are called directly, not declared in constructors, so teasing out relationships requires looking at every line of code.
  • Poor scalability. If you want to support multiple cases, it is difficult to expand, such as global data flow may be changed to multiple instances because of the micro front-end scheme, database connection pool to divide and conquer SQL into multiple instances, are possible, at the beginning of the system design should consider whether the future will maintain singleton.
  • Testability is poor because singletons are shared globally and isolation between test cases cannot be guaranteed.
  • Cannot use constructor to pass parameters.

In addition, the singleton pattern can be replaced by factory methods, so you don’t have to focus on one design pattern, you can use it in combination, and factory functions can also embed the singleton pattern.

conclusion

Singleton pattern is simple in concept and usage, which is a common solution in architecture design. However, the disadvantages of singleton pattern should be fully understood to prevent improper use.

The discussion address is: Intensive reading design Patterns — Singleton Singleton Patterns · Issue #278 · DT-fe /weekly

If you’d like to participate in the discussion, pleaseClick here to, with a new theme every week, released on weekends or Mondays. Front end Intensive Reading – Helps you filter the right content.

Pay attention to the front end of intensive reading wechat public account

Copyright Notice: Freely reproduced – Non-commercial – Non-derivative – Remain signed (Creative Commons 3.0 License)