Object-Oriented Design Pattern Summary 02 [Singleton Pattern]

Singleton Pattern【Singleton Pattern】【Singleton Pattern】

Guarantees that there is only one instance of a class, and provides a global access point to that instance.

Example 1:

 C# Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
public class  Singleton { public static readonly  Singleton Instance; /// <summary> /// Static constructor, which ensures multi-thread safety. In a multithreaded state, only one thread can access the static constructor. /// Static constructor, can only implement a static constructor with no parameters. /// You can use attributes to pass instantiated parameters. Or use the method to achieve. /// </summary> static  Singleton()     {         Instance =  new  Singleton();     } private  Singleton() { } }  

    
   

    

    
    
    
    
    




    

 

Example 2: [Simplified writing of Example 1]

 C# Code 
1
2
3
4
5
6
 
class  Singleton
{
    
public static readonly  Singleton Instance =  new  Singleton(); //Can automatically generate static constructors. private  Singleton() { } }    

    

 

Example 3: [with parameters]

 C# Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 
/// <summary>
/// Multi-threaded singleton mode with parameters
/// </summary>
public class  Singleton { private static  volatile  Singleton instance =  null ; // Prevent compiler fine-tuning. private static object  lockHelper =  new object (); //helper private  Singleton( int  i) { } public static  Singleton GetInstance( int  i)     { if  (instance ==  null )         { lock  (lockHelper) //lock             {  

    
 

    
     


    


    
 

        


            


                
if  (instance ==  null ) //双检查
                {
                    instance = 
new  Singleton(i);
                }
            }
        }
        
return  instance;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325720417&siteId=291194637