Design mode - singleton mode

Keywords: Design Pattern Singleton pattern

brief introduction

The class of a singleton object can only allow one instance to exist.

Many times, the whole system only needs to have a global object, which is conducive to coordinating the overall behavior of the system. For example, in a server program, the configuration information of the server is stored in a file. These configuration data are uniformly read by a single instance object, and then other objects in the service process obtain these configuration information through this single instance object. This approach simplifies configuration management in complex environments.

Singleton class, which defines a getInstance operation to allow customers to access its unique instance. GetInstance is a static method, which is mainly responsible for creating a unique instance.

Implementation steps

  1. Define the construction method of this class as a private method, so that the code in other places cannot instantiate the object of this class by calling the construction method of this class, and only the static method provided by this class can get the unique instance of this class;
  2. A static method is provided in the class. When we call this method, if the reference held by the class is not empty, this reference will be returned. If the reference held by the class is empty, an instance of the class will be created and the reference of the instance will be given to the reference held by the class.

Applicable scenarios:

  • 1. The environment where a unique sequence needs to be generated
  • 2. Objects that need to be instantiated frequently and then destroyed.
  • 3. Objects that take too much time or resources to create but are often used.
  • 4. An environment that facilitates communication between resources

Advantages and disadvantages


  • There is only one object in memory to save memory space;
  • Avoid frequent creation and destruction of objects, which can improve performance;
  • Avoid multiple occupation of shared resources and simplify access;
  • Provide a global access point for the entire system.


  • Not applicable to objects with frequent changes;
  • Abusing singleton will bring some negative problems. For example, in order to save resources, designing database connection pool objects as singleton classes may lead to too many programs sharing connection pool objects and connection pool overflow;
  • If the instantiated object is not used for a long time, the system will consider the object as garbage and be recycled, which may lead to the loss of object state;

Implementation mode

1. Hungry Han style

// Hungry Han style single case
public class Singleton1 {
    // Private static reference pointing to your own instance, actively created
    private static Singleton1 singleton1 = new Singleton1();
    // Private construction method
    private Singleton1(){}
    // Static public method and static factory method with their own instance as the return value
    public static Singleton1 getSingleton1(){
        return singleton1;

The method of class loading is to load on demand and load once. An instance is created when the class is loaded.

Advantages: this method is relatively simple, that is, instantiation is completed when the class is loaded. Thread synchronization problems are avoided.

Disadvantages: the instantiation is completed when the class is loaded, which does not achieve the effect of Lazy Loading. If this instance is never used from beginning to end, it will cause a waste of memory.

2. Lazy style

// Lazy single case
public class Singleton2 {
    // Private static reference to own instance
    private static Singleton2 singleton2;
    // Private construction method
    private Singleton2(){}
    // Static public method and static factory method with their own instance as the return value
    public static Singleton2 getSingleton2(){
        // Create passively, only when you really need to use it
        if (singleton2 == null) {
            singleton2 = new Singleton2();
        return singleton2;

The singleton instance is loaded late, that is, an object will be instantiated and handed over to its own reference only when it is actually used

This writing method has the effect of Lazy Loading, but it can only be used under single thread. If in multithreading, a thread enters

**if (singleton == null) * * the judgment statement block has not been executed in time, and another thread has passed the judgment statement. At this time, multiple instances will be generated. Therefore, this method cannot be used in a multithreaded environment.

3. Double locking mechanism

public class SingletonDemo3 {
   private volatile static SingletonDemo3 singletonDemo3;
   private SingletonDemo3(){}
   public static SingletonDemo3 getSingletonDemo3(){
           synchronized (SingletonDemo3.class){
                   singletonDemo3 = new SingletonDemo3();
       return singletonDemo3;

Using double detection synchronous delayed loading to create a singleton is a very excellent method, which not only ensures the singleton, but also effectively improves the running efficiency of the program

Advantages: thread safety; Delayed loading; High efficiency.

4. Static initialization

//Prevents derivation from occurring, which may increase the number of instances
    public sealed class Singleton
        //The common language runtime handles variable initialization when an instance is created when any member of the class is referenced for the first time
        private static readonly Singleton instance=new Singleton();
        private Singleton() { }
        public static Singleton GetInstance()
            return instance;

In practical application, C# and common language runtime also provide a "static initialization" method, which can solve the problem that it is unsafe in multi-threaded environment without developers explicitly writing thread safe code.

Posted by feddie1984 on Thu, 02 Sep 2021 14:16:36 -0700