Uniqueness of Singleton Mode

Source: Internet
Author: User

Uniqueness of Singleton Mode

Singleton mode:

The first method is the simplest, but thread security is not considered. problems may occur in multithreading.

public class Singleton{    private static Singleton _instance = null;    private Singleton(){}    public static Singleton CreateInstance()    {        if(_instance == null)        {            _instance = new Singleton();        }        return _instance;    }}

The second method considers thread security, which is a regular writing method and a classic cross

 

public class Singleton{    private volatile static Singleton _instance = null;    private static readonly object lockHelper = new object();    private Singleton(){}    public static Singleton CreateInstance()    {        if(_instance == null)        {            lock(lockHelper)            {                if(_instance == null)                     _instance = new Singleton();            }        }        return _instance;    }}

The third possibility is that C # is a special advanced language.

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

 

I. Singleton Mode

Features of Singleton mode:

  • A singleton class can have only one instance.
  • The Singleton class must create its own unique instance.
  • The Singleton class must provide this instance to all other objects.

Singleton mode application:

  • Each computer can have several printers, but only one Printer Spooler can be used to prevent two print jobs from being output to the Printer at the same time.
  • A table with an automatically numbered primary key can be used by multiple users at the same time, but the database can only allocate the next primary key number in one place. Otherwise, duplicate primary keys will appear.
Ii. Structure of Singleton mode:

The Singleton mode contains only one role, that is, Singleton. Singleton has a private constructor that ensures that you cannot directly instance it through new. In addition, this mode contains a static private member variable instance and a static public Method Instance (). The Instance method is responsible for verifying and instantiating itself, and then storing it in static member variables to ensure that only one Instance is created. (The thread issue and the special Singleton of C # will be discussed in detail later)

3. program example:

This program demonstrates the Singleton structure and does not have any practical value.

// Singleton pattern -- Structural example  using System;// "Singleton"class Singleton{  // Fields  private static Singleton instance;  // Constructor  protected Singleton() {}  // Methods  public static Singleton Instance()  {    // Uses "Lazy initialization"    if( instance == null )      instance = new Singleton();    return instance;  }}/// <summary>/// Client test/// </summary>public class Client{  public static void Main()  {    // Constructor is protected -- cannot use new    Singleton s1 = Singleton.Instance();    Singleton s2 = Singleton.Instance();    if( s1 == s2 )      Console.WriteLine( "The same instance" );  }}
4. Under what circumstances should I use the singleton mode:

There is a need to use Singleton mode: The Singleton mode should be used only when a system requires a class to have only one instance. If a class can coexist with several instances, do not use the singleton mode.

Note:

Do not use Singleton mode to access global variables. This violates the intention of the singleton mode and is best placed in the static members of the corresponding class.

Do not make the database connection into a single instance, because a system may have multiple connections to the database, and in the case of a connection pool, release the connection as soon as possible. Because the static member storage class instance is used in Singleton mode, resources may not be released in time, resulting in problems.

V. Implementation of the Singleton mode in the actual system

The following Singleton Code demonstrates the Server Load balancer object. In the Server Load balancer model, multiple servers can provide services. The task distributor selects a server at random to provide services to ensure task balancing (the actual situation is much more complex than this ). Here, only one task can be assigned to one instance, which is responsible for selecting servers and assigning tasks.

// Singleton pattern -- Real World example  using System;using System.Collections;using System.Threading;// "Singleton"class LoadBalancer{  // Fields  private static LoadBalancer balancer;  private ArrayList servers = new ArrayList();  private Random random = new Random();  // Constructors (protected)  protected LoadBalancer()  {    // List of available servers    servers.Add( "ServerI" );    servers.Add( "ServerII" );    servers.Add( "ServerIII" );    servers.Add( "ServerIV" );    servers.Add( "ServerV" );  }  // Methods  public static LoadBalancer GetLoadBalancer()  {    // Support multithreaded applications through    // "Double checked locking" pattern which avoids    // locking every time the method is invoked    if( balancer == null )    {      // Only one thread can obtain a mutex      Mutex mutex = new Mutex();      mutex.WaitOne();      if( balancer == null )        balancer = new LoadBalancer();      mutex.Close();    }    return balancer;  }  // Properties  public string Server  {    get    {      // Simple, but effective random load balancer      int r = random.Next( servers.Count );      return servers[ r ].ToString();    }  }}/// <summary>/// SingletonApp test/// </summary>///public class SingletonApp{  public static void Main( string[] args )  {    LoadBalancer b1 = LoadBalancer.GetLoadBalancer();    LoadBalancer b2 = LoadBalancer.GetLoadBalancer();    LoadBalancer b3 = LoadBalancer.GetLoadBalancer();    LoadBalancer b4 = LoadBalancer.GetLoadBalancer();    // Same instance?    if( (b1 == b2) && (b2 == b3) && (b3 == b4) )      Console.WriteLine( "Same instance" );    // Do the load balancing    Console.WriteLine( b1.Server );    Console.WriteLine( b2.Server );    Console.WriteLine( b3.Server );    Console.WriteLine( b4.Server );  }}
Vi. Singleton mode in C #

The unique language features of C # determine that C # has a unique method to implement the Singleton model. Here we will not repeat the reason here, and provide several results:

Method 1:

The following code uses the advantages of the. NET Framework Platform to implement the Singleton mode:

Sealed class Singleton
{
Private Singleton ();
Public static readonly Singleton Instance = new Singleton ();
}

This reduces the number of codes and solves the performance loss caused by thread problems. So how does it work?

Note that the Singleton class is declared as sealed to ensure that it will not be inherited by itself. Second, without the Instance method, the original _ instance member variable is changed to public readonly, it is initialized during declaration. Through these changes, we do get the Singleton mode, because during JIT processing, if the static attribute in the class is used by any method ,. NET Framework will initialize this property, so the Singleton class Instance can be created and loaded while initializing the Instance property. The private constructor and readonly ensure that Singleton will not be instantiated again, which is exactly the intent of Singleton's design pattern.

However, this also brings about some problems, such as the inability to inherit, the instance is initialized as soon as the program is run, and delayed initialization cannot be implemented.

For details, refer to the Microsoft MSDN article.

Method 2:

Since there is a problem with method 1, we have other methods.

public sealed class Singleton{  Singleton()  {  }  public static Singleton GetInstance()  {    return Nested.instance;  }      class Nested  {    // Explicit static constructor to tell C# compiler    // not to mark type as beforefieldinit    static Nested()    {    }    internal static readonly Singleton instance = new Singleton();  }}

This achieves delayed initialization and has many advantages. Of course, there are also some shortcomings. The article contains five Singleton implementations, which are described in detail in many aspects such as mode, thread, efficiency, and delay initialization.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.