设计模式笔记1:单件模式

单件模式(Singleton Pattern)

定义

确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。

双重锁定

 1 public sealed class Singleton
 2     {
 3         static Singleton instance = null;
 4         static readonly object padlock = new object();
 5 
 6         Singleton() { }
 7 
 8         public static Singleton Instance
 9         {
10             get 
11             {
12                 if (instance == null)//先判断是否为null再加锁
13                 {
14                     lock (padlock)
15                     {
16                         if (instance == null)
17                         {
18                             instance = new Singleton();
19                         }
20                     }
21                 }
22 
23                 return instance;
24             }
25         }
26     }
View Code

静态初始化

public sealed class Singleton
    {
        static readonly Singleton instance = new Singleton();

        static Singleton() { }

        /// <summary>
        /// 静态构造函数
        /// </summary>
        public static Singleton Instance
        {
            get { return instance; }
        }
    }
View Code

 

posted on 2013-05-26 15:11  那一年,那一天  阅读(164)  评论(0)    收藏  举报

导航