. net design pattern (1): 1.1 singleton pattern

Time:2022-5-7

summary

Singleton mode is to ensure that there is only one instance of the specified class at any time in the life cycle of the whole application, and provide the client with a global access point to obtain the instance.

Singleton pattern is a common software design pattern. Its core structure contains only a special class called singleton. The single instance mode can ensure that there is only one instance of a class in the system, and the instance is easy to be accessed by the outside world, so as to facilitate the control of the number of instances and save system resources. If you want only one object of a class to exist in the system, singleton mode is the best solution.


intention

Ensure that there is only one instance of a class and provide a global access point for that instance.


scene

  1. The task manager of windows is a typical singleton mode. Only one window can be opened at any time.

  2. The recycle bin of windows is also a typical single instance application. During the operation of the whole system, the recycle bin has maintained only one instance.

  3. The counter of the website is generally implemented in the single instance mode, otherwise it is difficult to synchronize.

  4. The log application of the application is generally implemented in the single instance mode. This is generally because the shared log file is always open, because there can only be one instance to operate, otherwise the content is not easy to add.

  5. The singleton mode is generally applied to the reading of configuration objects of web applications because the configuration file is a shared resource.

  6. The design of database connection pool generally adopts single instance mode, because database connection is a kind of database resource. The use of database connection pool in database software system is mainly to save the efficiency loss caused by opening or closing database connection. This efficiency loss is still very expensive, because it can be greatly reduced by using singleton mode for maintenance.

  7. The design of multithreaded thread pool generally adopts single instance mode, which is because the thread pool should facilitate the control of threads in the pool.

  8. The file system of the operating system is also a specific example of the implementation of large singleton mode. An operating system can only have one file system.

  9. Httpapplication is also a typical application of unit example. Familiar with ASP Net (IIS) throughout the request life cycle, people should know that httpapplication is also a singleton mode, and all httpapplication modules share an httpapplication instance


realization

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 get the unique instance of this class through the static method provided by this class;
2. Provide a static method in the class. When we call this method, if the reference held by the class is not empty, we will return this reference. If the reference held by the class is empty, we will create an instance of the class and assign the reference of the instance to the reference held by the class.

Hungry Han style

  • Static constant (classical writing)

public class Singleton
{
    private static Singleton _instance = new Singleton();
    private Singleton() { }

    public static Singleton Instance()
    {
        return _instance;
    }
}

Applicable: single / multi thread
Mode: hungry Han formula (static constant) [available]
Advantages: the writing method is relatively simple and avoids the problem of thread synchronization
Disadvantages: delayed loading is not realized

  • Static code block

public class Singleton2
{
    private static Singleton2 _instance;

    static Singleton2()
    {
        _instance = new Singleton2();
    }

    private Singleton2(){}

    public Singleton2 Instance()
    {
        return _instance;
    }
}

Applicable: single / multi thread
Mode: hungry Chinese style (static code block) [available]
Advantages: the writing method is relatively simple and avoids the problem of thread synchronization
Disadvantages: delayed loading is not realized

Lazy style

public class Singleton3
{
    private static Singleton3 _instance;

    private Singleton3() { }

    public static Singleton3 Instance()
    {
        return _instance ?? (_instance = new Singleton3());
    }
}

Applicable: single thread
Mode: lazy (thread unsafe) [not available]
Advantages: suitable for single thread, simple implementation and delayed loading
Disadvantages: multithreading is unsafe and violates the principle of single column mode

  • Thread unsafe

public class Singleton4
{
    private static Singleton4 _instance;
    private static readonly object SyncObject = new object();

    private Singleton4() { }

    public static Singleton4 Instance()
    {
        lock (SyncObject)
        {
            if (_instance == null)
            {
                _instance = new Singleton4();
            }
        }
        return _instance;
    }
}

Applicable: single thread
Mode: lazy (thread safe) [not recommended]
Advantages: thread safety; Delayed loading;
Disadvantages: this implementation method increases additional overhead and loses performance (when there are multiple calls, the first one will enter lock, while others will wait until the first one is completed, and the subsequent ones will access and wait in turn…)

  • Double check lock

public class Singleton5
{
    private static Singleton5 _instance;
    private static readonly object SyncObject = new object();

    private Singleton5() { }

    public static Singleton5 Instance()
    {
        if (_instance==null)
        {
            lock (SyncObject)
            {
                if (_instance == null)
                {
                    _instance = new Singleton5();
                }
            }
        }
        return _instance;
    }
}

Applicable: single / multi thread
Mode: double check locking (thread safe) [recommended]
Advantages: thread safety; Delayed loading; High efficiency (it will only be instantiated once. First, it will judge whether it has been instantiated. If it has been instantiated, it will directly return to the instance without entering lock; if it has not been instantiated, it will not hurt to enter lock, even if it is multiple calls. The first call will be instantiated, and the second one will judge whether it has been instantiated again when entering lock, so that the thread will not be blocked.)
Disadvantages: basically no

  • Static inner class

public class Singleton6
{
    private Singleton6() { }

    private static class SingletonInstance
    {
        public static Singleton6 Instance = new Singleton6();
    }

    public static Singleton6 Instance()
    {
        return SingletonInstance.Instance;
    }
}

Applicable: single / multi thread
Mode: static inner class (thread safe) [recommended]
Advantages: thread insecurity is avoided; Delayed loading; efficient (the mechanism of this method is similar to that of the hungry Chinese method: class loading mechanism is adopted to ensure that there is only one thread when initializing the instance. The difference is that the hungry Chinese method instantiates as long as the singleton class is loaded, without the role of lazy loading; while the static internal class method does not instantiate immediately when the singleton class is loaded, but calls the instance method when instantiation is needed CE class to complete the instantiation of singleton.)
Disadvantages: basically no