Static Singleton Mode

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.