Non-lazy version of the common Singleton implementation:
Public Sealed classSingletonclass:isingleton {PrivateSingletonclass () {//The private contructors } Public StaticIsingleton Instance {Get { if(Instance = =NULL) { Lock(instancelock) {if(Instance! =NULL) { returninstance; } instance=NewSingletonclass (); } } returninstance; } } Private StaticIsingleton instance; Private Static ReadOnly ObjectInstancelock =New Object(); Private BOOLisdisposed; //Other Properties Public voidDispose () { This. Dispose (true); Gc. SuppressFinalize ( This); } Private voidDispose (BOOLdisposing) { if(! This. isdisposed) { if(disposing) {//Dispose the objects you declared } This. isdisposed =true; } } } Public Interfaceisingleton:idisposable {//Your interface methods}
Lazy version of a singleton implementation:
Public Sealed classSingletonclass:isingleton {PrivateSingletonclass () {//The private contructors } Public static Isingleton Instance = new Lazy<isingleton> (() = new New Singletonclass ()). Value;
Private Static ReadOnly ObjectInstancelock =New Object(); Private BOOLisdisposed; //Other Properties Public voidDispose () { This. Dispose (true); Gc. SuppressFinalize ( This); } Private voidDispose (BOOLdisposing) { if(! This. isdisposed) { if(disposing) {//Dispose the objects you declared } This. isdisposed =true; } } } Public Interfaceisingleton:idisposable {//Your interface methods}
Comparative analysis:
Use lazy<t> to initialize, making the code look more concise and understandable. In fact, the non-lazy<t> version of the singleton implementation is essentially a simple object of lazy implementation.
Generally, for some objects that occupy large memory, the lazy method is often used to initialize for optimization purposes.
C # Singleton mode lazy<t> implementation version