Single-Case mode:
In the multi-threaded program development process often encounter singleton mode [single-piece mode], it is not based on the call of the client program to generate a new instance, but to control the number of instances of a type only one. In other words, the singleton pattern is guaranteed to have only one instance of the specified class at any given time throughout the life of the application, and provides a global access point for the client to get the instance.
Next look at a classic singleton pattern:
public class singleinstance{ private static singleinstance _instance=; private SingleInstance () {} public SingleInstance getinstance () {if (null = = _instance) {_instance =new SingleInstance (); return _instance; }}
View Code
However, the above classic singleton mode does not take into account the problem of multi-threaded concurrency, the following code is to improve the above code to solve the multi-threaded concurrency problem, multi-threaded singleton mode [Lazy mode]:
Public classsingleinstance{Private StaticSingleInstance _instance=NULL; Private StaticObject _lock=NewObject (); Privatesingelinstance () {} Publicsingleinstance getinstance () {if(NULL==_instance) { Lock(_lock) {if(NULL==_instance) {_instance=Newsingleinstance (); } } } return_instance; }}View Code
There is another a hungry man mode, the program code is as follows:
Public class singleinstance{ privatestaticreadonly singleinstance _instance=New singleinstance (); Private singleinstance () { } public singleinstance getinstance () { return _instance;} }
View Code
The ReadOnly key used by this pattern can be used with static to specify that the constant is of category level, its initialization is implemented by the static constructor, and can be compiled at run time. In this mode, there is no need to solve the thread safety problem yourself, the CLR will fix it for us. As a result of this class being loaded, the class is automatically instantiated without having to instantiate a unique singleton object after the first call to GetInstance ().
Cond...
Parsing common programming patterns in the C # development process