A Design Pattern a Day is designed to get a first look at design patterns and is currently implemented in javascript (for a living) and Python (purely for fun). Of course, there are multiple implementations of each design pattern, but this small volume only documents the most straightforward

  1. If the Internet speed is too slow, please go to the original address of the singleton pattern of one Design pattern a day
  2. Welcome to my site for more dry goods + free tutorials:godbmw.com

0. Project address

  • Source code address for this lesson
  • A Design Pattern a day address

1. What is the singleton pattern?

Singleton pattern definition: Ensures that a class has only one instance and provides a global access point to that instance.

2. Usage of singleton mode

If a class is responsible for connecting to a database’s thread pool, logging logic, and so on, the singleton pattern is needed to ensure that objects are not created repeatedly to reduce overhead.

3. Code implementation

It should be noted that the singleton pattern of the following implementations is “lazy singleton” : object instances are created only when the user needs them.

3.1 python3 implementation

class Singleton:
  # use instance as static variable
  __instance = None

  @staticmethod
  def get_instance(a):
    if Singleton.__instance == None:
      If no instance is initialized, the initialization function is called
      Generate instance instance for Singleton
      Singleton()
    return Singleton.__instance

  def __init__(self):
    ifSingleton.__instance ! =None:
      raise Exception("Please get an instance by get_instance()")
    else:
      Generate instance instance for Singleton
      Singleton.__instance = self

if __name__ == "__main__":

  s1 = Singleton.get_instance()
  s2 = Singleton.get_instance()

  Check whether the memory address is the same
  print(id(s1) == id(s2))
Copy the code

3.2 javascript implementation

const Singleton = function() {};

Singleton.getInstance = (function() {
  // Because ES6 has no static type, instance cannot be accessed from outside the function
  let instance = null;
  return function() {
    // Check whether an instance exists
    if(! instance) { instance =new Singleton();
    }
    returninstance; }; }) ();let s1 = Singleton.getInstance();
let s2 = Singleton.getInstance();

console.log(s1 === s2);
Copy the code