Design Pattern 5: Singleton Pattern)

Source: Internet
Author: User

The Singleton Mode means that there is only one instance. The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system. This class is called a singleton class.

The Singleton mode has three key points:

  1. Point. A class can only have one instance;
  2. It must create this instance by itself
  3. It must provide this instance to the entire system.

Some resource managers are often designed to work in singleton mode.

The Singleton mode in C # ensures that a class has only one instance and provides a global access point to it.

Implementation points:

  1. The Singleton mode is to restrict rather than improve the creation of classes.
  2. The Singleton mode generally does not support the Icloneable interface, because it may lead to multiple object instances, which is contrary to the original intention of the singleton mode.
  3. The Singleton mode generally does not support serialization, which may also lead to multiple object instances.
  4. In Singleton mode, only object creation management is taken into account, and destruction management is not taken into account. In terms of the platform and object overhead supporting garbage collection, we generally do not need to perform special management on its destruction.
  5. The core of understanding and extending the singleton mode is "if you want to control the arbitrary calls of a new constructor to a class"

Advantages:

  1. Instance control: Singleton prevents other objects from instantiating copies of its own Singleton object, so that all objects can access a unique instance.
  2. Flexibility: Because the class controls the instantiation process, the class can be more flexible to modify the instantiation process.

Disadvantages:

  1. Object lifetime: Singleton cannot solve the problem of deleting a single object. In the language that provides memory management (for example, the. NET Framework-based language), only the Singleton class can cause the instance to be unallocated because it contains private references to the instance. In some languages (such as C ++), other classes can be deleted. However, this will cause floating references in the Singleton class.

Practicality:

When the class has only one instance and the customer can access it from an access point in the total region.

When this unique instance should be extensible through subclass, and the customer should be able to use an extended instance without changing the code.

Application scenarios:

  1. Each computer can have a dry Printer, but only one Printer Spooler can be used to prevent two Printer jobs from being output to the Printer at the same time.
  2. The PC may have several serial ports, but only one instance with a Com1 port is allowed.
  3. There can be only one window manager in the system
  4. In. NET Remoting, the server activates the Singleton object in the object to ensure that all client program requests are processed by only one instance.
  5.  

Classic Implementation of Singleton mode:

  1. Public sealed class Singleton

{

Static Singleton instance = null;

 

Singleton ()

{

}

 

Public static Singleton Instance

{

Get

{

If (instance = null)

{

Instance = new Singleton ();

}

Return instance;

}

}

}

This is the simplest implementation method, but this implementation is not secure for the thread. When two or more threads determine that instance = null at the same time and the result is true, multiple instances are created, which violates the singleton mode principle. In fact, in the above Code, it is possible that the object instance has been created before the expression value is calculated, but the memory model does not guarantee that the object instance is found before the second thread is created.

This implementation method is called "inert instantiation" and does not require singleton to be instantiated when an application starts.

2.

  public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();
 
    Singleton()
    {
    }
 
    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}

This implementation method is secure for the thread, but this implementation method adds additional overhead and reduces performance.

3.

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();
 
    Singleton()
    {
    }
 
    public static Singleton Instance
    {
        get
        {
            if (instance==null)
            {
                lock (padlock)
                {
                    if (instance==null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}

This implementation method is safe for the thread. At the same time, the thread does not lock every time. It is locked only when it determines that the object instance is not created. Solve the thread concurrency problem, but cannot implement delayed initialization.

4.

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

This implementation method creates an instance when a class member is referenced for the first time. The Common Language Runtime Library processes variable initialization. The disadvantage of this method is that it has less control over the instantiation mechanism. In most cases, static Initialization is the preferred method to implement Singleton in. NET.

5. public sealed class Singleton

{

Singleton ()

{

}

 

Public static Singleton Instance

{

Get

{

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 ();

}

}

The initialization of this implementation method is completed by a static member of the Nested class, thus implementing delayed initialization. Is a recommended implementation method.

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.