What is static Singleton mode?
Static Singleton pattern is the pattern I have summarized in practice. The main problem is that when a dependency is known as a singleton application in advance, provide access through static cache of this dependency. Of course, there are many solutions to this problem, but this is only one of them.
Implementation Details
/// <Summary> /// Static Singleton /// </Summary> /// <Typeparam name = "tclass"> Singleton type </Typeparam> Public Static Class Singleton <tclass> Where Tclass: Class , New (){ Private Static Readonly Object _ Lock = New Object (); Private Static Tclass _ instance = Default (Tclass ); /// <Summary> /// Obtain a singleton instance /// </Summary> Public Static Tclass getinstance (){ Return Instance ;} /// <Summary> /// Singleton instance /// </Summary> Public Static Tclass instance { Get { If (_ Instance = Null ){ Lock (_ Lock ){ If (_ Instance = Null ) {_ Instance = New Tclass (); // Must be public Constructor }}} Return _ Instance ;}} /// <Summary> /// Set a singleton instance /// </Summary> /// <Param name = "instance"> Singleton instance </Param> Public Static Void Set (tclass instance ){ Lock (_ Lock) {_ instance = Instance ;}} /// <Summary> /// Reset a singleton instance /// </Summary> Public Static Void Reset (){ Lock (_ Lock) {_ instance = Default (Tclass );}}}
Application Testing
Class Program { Interface Iinterfacea { String Getdata ();} Class Classa: iinterfacea { Public String Getdata (){ Return String . Format ( " This is from classa with hash [{0}]. " , This . Gethashcode ());}} Static Void Main ( String [] ARGs ){ String Data1 = Singleton <classa> . Getinstance (). getdata (); console. writeline (data1 ); String Data2 = Singleton <classa> . Getinstance (). getdata (); console. writeline (data2); console. readkey ();}}
Test Results