I. Introduction
The Singleton mode is mainly used to ensure that a class only has one instance while the program is running and provides a global entry point. Singleton is the simplest of the 24 standard design patterns described by gof. However, with the passage of time, the single-instance Implementation described by gof cannot fully satisfy the actual application.
"Ensure a class has only one instance, and provide a global point of access to it"
Ii. motivation (Application Scenario)
Almost every application requires a region from which to globally access and maintain certain types of data. This is also the case in object-oriented (OO) systems where only a set of predefined instances of one class or one class can be run at any given time.
1. When you use a class to maintain the incremental counter, this simple counter class needs to track the integer used in multiple application fields. This class needs to be able to increase the counter and return the current value. In this case, only one class instance should be used to maintain the integer, rather than other class instances to maintain the integer.
2. 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.
3. There may be several serial ports on the PC, but there can only be one instance with a COM1 port.
4. There can only be one window manager in the system.
5. In net remoting, the server activates the sigleton object in the object to ensure that all client program requests are processed by only one instance.
6. generally, the log application of an application is implemented in singleton mode. This is generally because the shared log file is always in the open state, because only one instance can be operated; otherwise, the content cannot be appended.
III. C # implementation
1. Single-threaded implementation
Single-threaded Singleton mode Implementation/*** Singleton mode single-threaded implementation. It cannot be guaranteed that only one instance is generated in single-threaded mode. */Class Singleton {Private Static Singleton instance; // define the constructor as private to prevent the class from being instantiated externally. // If You Need to inherit the class definition, you can change private to protectedprivate Singleton () {} public static Singleton getinstance () {// when it is in a multi-threaded environment, multiple Threads may generate multiple instances in the code execution order, which violates the original intention of this mode if (instance = NULL) {instance = new Singleton ();} return instance ;}}
It can be said that it is a standard Singleton code.
Advantages:
Because the instance is inInstanceThe property method is created internally, so the class can use additional features (for example, instantiate the subclass), even if it may introduce unwanted dependencies.
It is called "lazy instantiation" until the object requires an instance to be generated ". Lazy instantiation avoids unnecessary instantiation during application startupSingleton.
Disadvantages:
In a multi-threaded environment, it is insecure. If different threads in the execution process enterInstanceAttribute method, you may create multipleSingletonObject instance. Each thread executes the following statements and determines that a new instance must be created.
2. Multithreading
The multi-threaded Singleton mode implements the class Singleton {// volatile keyword. This should tell the compiler not to re-sort the code and give up optimization. Make sure that you can access the instance variables only after the instance variables are allocated. // Prevent code control from being invalid due to compiler optimization. Private Static volatile Singleton instance; // use the syncroot instance to lock (instead of locking the type itself) to avoid deadlocks. Private Static object syncroot = new object (); Private Singleton () {} public static Singleton instance {get {// double check lock-double-check locking // The double-check locking method solves the thread concurrency problem, at the same time, avoid exclusive locking in calls to each instance attribute method. If (instance = NULL) {lock (syncroot) {If (instance = NULL) instance = new Singleton () ;}} return instance ;}}}
Advantage: Because the generation of instances is controlled by the user, non-default constructor can be expanded and parameters can be passed.
Disadvantage: relatively complicated implementation
3. C # simplified edition
Because the C # and common language runtime libraries also provide a "static initialization" method, this method can solve the problem of multi-thread creation without explicitly writing thread security code.
Concise implementation 1 Public sealed class Singleton {// The variable is marked as readonly, which means that only variables can be allocated during static initialization (the example shown here) or in the class constructor. Private Static readonly Singleton instance = new Singleton (); Private Singleton () {}public static Singleton instance {get {return instance ;}}}
More concise method:
Concise implementation 1 Public sealed class Singleton {public static readonly Singleton instance = new Singleton (); Private Singleton (){}}
Because a static constructor belongs to a class and does not belong to any instance, this constructor will only be executed once, and before creating the first instance of this class or referencing any static members. net Automatic Call.
1. Because the static constructor is called by. net, access modifiers such as public and private are not required.
2. When the first class instance is created or any static member is referenced,. Net automatically calls the static constructor to initialize the class. (We cannot call it or know when it will be called)
3. Static constructor belongs to the class and constructor belongs to the instance. They do not conflict with each other. The static constructor runs only once.
Disadvantage: In this solution. NET FrameworkResponsible for initialization. Non-Default constructors or other tasks cannot be used before instantiation. In most cases, static Initialization is performed in. NetImplementationSingleton.
Iv. Summary
The single-thread version, multi-thread version, and simplified version have their own applications. Without such implementation, it is the best.
Summarize the above three implementation methods to determine whether to pass parameters or execute other tasks when creating a singleton instance. That is:
1. No other tasks are required.
The use of the simplified version ensures the safe use of a single thread and multiple threads, while the amount of code is small.
2. Required
Generally, all are single-threaded versions. It is created using a single thread. If the program has multi-threaded applications, the application uses the dual-check multi-thread implementation.
Reference:
Http://msdn.microsoft.com/zh-cn/library/ff650316.aspx