设计模式--单例模式

  今天开始要学习设计模式了!!!!

 

  单例:

  自己的理解:就是不管什么时候,用的都是一个类的同一个实例。

  别人的说法:保证一个类仅有一个实例,并提供一个访问它的全局访问点(设计模式)。

 

  第一种写法:

  

 1 /// <summary>
 2 /// 使用类的静态变量,从构造函数创建实例
 3 /// </summary>
 4 public class Singleton
 5 {
 6     private static Singleton instance;
 7 
 8     public Singleton()
 9     {
10         if (null == instance)
11         {
12             instance = new Singleton();
13         }
14     }
15 
16 }

 

第二种写法:

 

public class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
       
    }

    public static Singleton getInstance()
    {
        if (instance == null)
        {
            instance = new Singleton();
        }
        return instance;
    }

}

 

第三种方式:也是最推荐的方式(双重锁定)

 

 1 /// <summary>
 2 /// 防止多线程访问创建多个实例
 3 /// </summary>
 4 public class Singleton
 5 {
 6     //静态变量
 7     private static Singleton instance;
 8  
 9     //程序运行时创建一个静态只读的进程辅助对象
10     private static readonly object synlock = new object();
11 
12     private Singleton()
13     {
14        
15     }
16 
17     public static Singleton getInstance()
18     {
19         if (instance == null) //必须先判断是否为空
20         {
21             lock(synlock)  //在同一时刻加了锁的那部分程序只有一个线程可以进入
22             {
23                 if (instance == null) //再次判断为空
24                 {
25                     instance = new Singleton();
26                 }
27             }
28         }
29         return instance;
30     }
31 
32 }

 

 

 

  

 

posted @ 2016-12-22 15:10  汇源果汁cp  阅读(148)  评论(0)    收藏  举报