码迷,mamicode.com
首页 > Windows程序 > 详细

C#设计模式-单例模式

时间:2015-03-15 22:36:06      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:

单例模式的定义:

  保证一个类仅只有一个实例,并提供一个访问它的全局访问点。

从定义我相信大家不可以很好的明白设计思想,让我们看一段代码。

技术分享
 1     class Singleton
 2     {
 3         private static Singleton instance;
 4         private static readonly object syncRoot = new object();
 5         private Singleton()
 6         {
 7         }
 8 
 9         public static Singleton GetInstance()
10         {
11             if (instance == null)
12             {
13 
14                 lock (syncRoot)
15                 {
16 
17                     if (instance == null)
18                     {
19                         instance = new Singleton();
20                     }
21                 }
22             }
23             return instance;
24         }
25 
26     }
View Code

 以上函数就是单例模式的核心代码,创建唯一的实例。

主程序示例如下:

技术分享
 1   static void Main(string[] args)
 2         {
 3             Singleton s1 = Singleton.GetInstance();
 4             Singleton s2 = Singleton.GetInstance();
 5 
 6             if (s1 == s2)
 7             {
 8                 Console.WriteLine("Objects are the same instance");
 9             }
10 
11             Console.Read();
12         }
View Code

主程序两次调用,实质只创建一个实例。

C#设计模式-单例模式

标签:

原文地址:http://www.cnblogs.com/Smart-boy/p/4340427.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!