Design Pattern-Singleton

Source: Internet
Author: User

Singleton mode requires that a class has only one instance. You must create your own unique instance, provide this instance to all other objects, and provide a global access point. This raises a question: how to bypass the conventional constructor and provide a mechanism to ensure that a class has only one instance? When a customer program calls a class, it does not consider whether the class can only have one instance or other issues. Therefore, this should be the responsibility of the class designer, not the responsibility of the class user. From another perspective, the Singleton model is actually a responsibility model. Because we have created an object and this object plays a unique role, in this separate object instance, it concentrates all the power of the class to which it belongs, at the same time, it is also responsible for exercising this kind of power! 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 Singleton mode is to restrict the creation of classes, rather than to improve the creation of classes. The instance constructor In the Singleton class can be set to Protected to allow subclass derivation. The Singleton mode generally does not support the Icloneable interface, this may cause multiple object instances, which is contrary to the original intention of Singleton mode. Singleton mode generally does not support serialization, which may also lead to multiple object instances, this is also contrary to the original intention of the Singleton model. Singleton only considers object creation management and does not consider destruction management. In terms of the overhead of platforms and objects supporting garbage collection, we generally do not need to perform special management on the destruction. The core of understanding and extending the Singleton mode is "how to control the arbitrary calls of a new constructor to a class "; you can easily modify a Singleton so that it has a few instances, which is allowed and meaningful.
Using System;
Class Singleton
{
Private static Singleton instance;
Protected Singleton (){}
Public static Singleton Instance ()
{

If (instance = null)
Instance = new Singleton ();
Return instance;
}
}

Public class Client
{
Public static void Main ()
{
Singleton s1 = Singleton. Instance ();
Singleton s2 = Singleton. Instance ();
If (s1 = s2)
Console. WriteLine ("The same instance ");
}
}
Comparison of several simple implementations and advantages and disadvantages
1:
Public sealed class Singleton
{
Static Singleton instance = null;
 
Singleton ()
{
}
 
Public static Singleton Instance
{
Get
{
If (instance = null)
{
Instance = new Singleton ();
}
Return instance;
}
}
}
This method is not secure for threads, because multiple instances of the Singleton class may be obtained in a multi-threaded environment. If there are two threads to judge at the same time (instance = null) and the result is true, then both threads will create Singleton-like instances, 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 discovered before the second thread is created; because the Instance is created inside the Instance property method, the class can use additional features (for example, instantiate the subclass), even if it may introduce unwanted dependencies, it is called "inert instantiation" until the object requires an instance to be generated ". Inert instantiation avoids unnecessary singleton instantiation at application startup.
2:
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.
(From: http://www.cnblogs.com/huqingyu/archive/2004/07/09/22721.aspx)
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.
3:
Public sealed class Singleton
{
Singleton ()
{
}
 
Public static Singleton Instance
{
Get
{
Return Nested. instance;
}
}

Class Nested
{
Static Nested ()
{
}

Internal static readonly Singleton instance = new Singleton ();
}
}
Here, the initialization work is completed by a static member of the Nested class, which achieves delayed initialization and has many advantages, which is a recommended practice.
4:
Public class DataProvider: DataHelper
 
{

Private DataProvider ()
{
}

Static DataProvider ()
{
If (dp = null)
{
Dp = new DataProvider ();
}

SqlXmlPath = HttpContext. Current. Server. MapPath ("SqlXML. xml ");
}
Private static readonly DataProvider dp = null;
Private static readonly string sqlXmlPath;

Public static DataProvider Instance
{
Get
{
Return dp;
}
}
}
The Singleton design pattern is a very useful mechanism for providing a single access point in an object-oriented application.

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.