Recommendation 105: Use private constructors to harden a single case
Singleton refers to a type that generates only one instance object. A simple implementation of the singleton is as follows:
Static voidMain (string[] args) {Singleton.Instance.SampleMethod (); } Public Sealed classSingleton {StaticSingleton instance =NULL; Public StaticSingleton Instance {Get { returninstance==NULL?NewSingleton (): instance; } } Public voidSampleMethod () {//omitted } }
A singleton type singleton is used in the main method.
The singleton first provides a private variable of its own type. In the instance property, it is the only instance responsible for creating the type itself. If you want to use the type externally, you must pass the instance property, with a special emphasis on the "must" two words.
There is a problem in the code above: although in the caller code, we get the type instance through the instance property. However, the type does not prevent itself from being created externally. Because the type singleton does not provide a construction method, the compiler creates a constructor for it by default, and the access modifier for the default constructor is public. This will not prevent the following code from being used externally:
New Singleton (); S.samplemethod ();
This obviously loses the meaning of a single case. In fact, this causes multiple singleton objects to be present in the system. To prevent this from happening, you must add a private constructor for the singleton type. The improved version of Singleton is as follows:
Public Sealed classSingleton {StaticSingleton instance =NULL; //restrict instances from being created externally PrivateSingleton () {} Public StaticSingleton Instance {Get{returnInstance = =NULL?NewSingleton (): instance;} } Public voidSampleMethod () {//omitted } }
Note: The final singleton is not thread-safe. In the case of multithreading, it is possible to produce a second instance. One of the most famous techniques for a single case is the "double locking" technique. With double locking, the thread-safe version of the Singleton is:
Public Sealed classSingleton {StaticSingleton instance =NULL; Static ReadOnly Objectpadlock=New Object(); //restrict instances from being created externally PrivateSingleton () {} Public StaticSingleton Instance {Get { if(Instance = =NULL) { Lock(padlock) {if(Instance = =NULL) {instance=NewSingleton (); } } } returninstance; } } Public voidSampleMethod () {//omitted } }
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 105: Using private constructors to harden a single case