This article has participated in the Denver Nuggets Creators Camp 3 “More Productive writing” track, see details: Digg project | creators Camp 3 ongoing, “write” personal impact.

Aliases: Singleton, Singleton

A, intentions

The singleton pattern is a creative design pattern that allows you to ensure that there is only one instance of a class and provide a global node to access that instance.


Second, motivation

In program development, there are often some special classes, they must be guaranteed in the system only one instance, to ensure their logical correctness and good efficiency.

The question arises: how can we ensure that there is only one instance of a class that can be easily accessed?

You might immediately think: define a global variable that allows this instance to be accessed, and I promise I’ll only instantiate this object once in this program. Of course, I’m sure you can do that as a programmer.

This should be the responsibility of the designer of the class, not the user.

This leads to the singleton design pattern: make the class itself responsible for keeping its unique instance. This class ensures that no other instances can be created, and it provides a method to access modified instances.


Three, the structure is

  1. The Singleton class declares a static method called getInstance to return an identical instance of its class.
  2. The constructor of a singleton must be hidden from Client code. Calling the get instance method must be the only way to get a singleton.

Four, advantages and disadvantages

Advantages:

  • Can be derived: Can be set in the instance constructor of a singleton class to allow subclasses to be derived.
  • Controlled access: Because a singleton class encapsulates its unique instance, it has strict control over how and when other programs access it.
  • You get a global access node that points to the instance.
  • A singleton is initialized only when it is first requested.

Disadvantages:

  • It violates the principle of single responsibility.
  • The singleton pattern generally does not support serialization, as this can also lead to multiple object instances.
  • In multithreaded environments, special processing is required to avoid multiple threads creating singleton objects.

Five, application scenarios

The singleton pattern is suitable for application scenarios if only one instance of a class in a program is available to all clients, the singleton pattern can be used.

The singleton pattern prohibits the creation of objects of its own class by any means other than a special build method. This method creates a new object, but returns an existing object if it has already been created.

If you need more control over global variables, you can use the singleton pattern.

Unlike global variables, singletons guarantee that only one instance of a class exists. A cached instance cannot be replaced in any way other than by the singleton class itself.

  • PS: You can adjust the limits and set the number of singleton instances to be generated at any time, just by changing the method used to get the instance.

Six, code implementation

Implementation method:

  1. Add a private static member variable to the class to hold a singleton instance.
  2. Declare a public static build method (property) to get a singleton instance.
  3. Implement lazy initialization in static methods (properties). This method creates a new object the first time it is called and stores it in a static member variable. The instance is returned each time the method is called thereafter.
  4. Make the constructor of the class private. Class static methods can still call constructors, but other objects cannot.

Sample code:

class Singleton
{
    private static Singleton _instance; / / 1.

    public static Singleton Instance / / 2.3.
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return_instance; }}private Singleton(){}/ / 4.
}
Copy the code

Multithreaded singleton

Multiple singletons may be created when multiple threads are used to access the above code. Modify the code as follows to implement the singletons in multiple threads:

A lock is used to ensure that only one thread accesses the construct at a time

 class SingletonThread
 {
    private static volatile SingletonThread _instance;

    private static object lockHelper = new Object { };

    public static SingletonThread Instance
    {
        get
        {
            // Double check, to avoid additional performance consumption
            if(_instance== null)
            {
            	// When the first thread runs here, the lock will be locked,
            	// When the second thread runs the method, it first detects the lock state and suspends to wait for the first thread to unlock
                lock (lockHelper)
                {
                	 if(_instance== null)
                	 {
                   		_instance= newSingletonThread(); }}}return_instance; }}// Private construct
    private SingletonThread(){}}Copy the code

Volatile: Portals


Another way of writing, using static constructors and read-only genera, (disadvantage: parameterized construction is supported)

.NET mechanisms control static constructors to ensure that only one thread is executed

class SingletonRead {

   // The static constructor is executed whenever it is accessed, not instantiated
   public static readonly SingletonRead Instance = new Singleton_Read();

    / / equivalent to the
    //public static readonly SingletonRead Instance;
    //static SingletonRead ()
    / / {
    // Instance = new SingletonRead ();
    / /}
        
    private Singleton_Read(){}}Copy the code

Design Patterns series of blog posts sample code Engineering: Links