大话设计模式读书笔记17----单例模式(Singleton)

单例模式(Singleton):保证一个类仅有一个实例,并提供一个访问它的全局访问点。

1、多线程:lock是确保一个线程在临界区,另一个线程不能进入临界区。如果其他线程试图进入锁定的代码,它将一直等待。

代码
 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.Text;
 4 
 5  namespace  Singleton
 6  {
 7       class  Program
 8      {
 9           static   void  Main( string [] args)
10          {
11              Singleton s1  =  Singleton.GetInstance();
12              Singleton s2  =  Singleton.GetInstance();
13               if  (s1  ==  s2)
14              {
15                  Console.WriteLine( " 两个对象相同 " );
16              }
17          }
18      }
19       class  Singleton
20      {
21           private   static  Singleton instance;
22           private   static   readonly   object  syncRoot  =   new   object ();
23           private  Singleton()
24          {
25   
26          }
27           public   static  Singleton GetInstance()
28          {
29               lock  (syncRoot)
30              {
31                   if (instance == null )
32                  {
33                      instance  =   new  Singleton();
34                  }
35              }
36               return  instance;
37          }
38      }
39  }

2、双重锁定

代码
 1  using  System;
 2  using  System.Collections.Generic;
 3  using  System.Text;
 4 
 5  namespace  Singleton
 6  {
 7       class  Program
 8      {
 9           static   void  Main( string [] args)
10          {
11              Singleton s1  =  Singleton.GetInstance();
12              Singleton s2  =  Singleton.GetInstance();
13               if  (s1  ==  s2)
14              {
15                  Console.WriteLine( " 两个对象相同 " );
16              }
17          }
18      }
19       class  Singleton
20      {
21           private   static  Singleton instance;
22           private   static   readonly   object  syncRoot  =   new   object ();
23           private  Singleton()
24          {
25   
26          }
27           public   static  Singleton GetInstance()
28          {
29               if  (instance  ==   null )
30              {
31                   lock  (syncRoot)
32                  {
33                       if  (instance  ==   null )
34                      {
35                          instance  =   new  Singleton();
36                      }
37                  }
38              }
39               return  instance;
40          }
41      }
42  }


 

 

你可能感兴趣的:(Singleton)