首页 > 其他 > 详细

设计模式读书笔记-单件模式(创建型模式)

时间:2015-07-02 20:55:42      阅读:200      评论:0      收藏:0      [点我收藏+]

让一个类只有一个对象,全局唯一

非多线程模式,实现方法:

方法1:

技术分享
1     public class SingletonTest
2     {
3         public static readonly SingletonTest Instance = new SingletonTest();
4         private SingletonTest() { }
5     }
View Code

方法2:

技术分享
1     public class SingletonTest
2     {
3         public static readonly SingletonTest Instance;
4         static SingletonTest()
5         {
6             Instance = new SingletonTest();
7         }
8         private SingletonTest() { }
9     }
View Code

 多线程模式,实现方法:

技术分享
 1     public class SingletonTest
 2     {
 3         private static volatile SingletonTest instance = null;
 4         private static object lockobj = new object();
 5         private SingletonTest() { }
 6         public static SingletonTest Instance
 7         {
 8             get
 9             {
10                 if (instance == null)
11                 {
12                     lock (lockobj)
13                     {
14                         if (instance == null)
15                         {
16                             instance = new SingletonTest();
17                         }
18                     }
19                 }
20                 return instance;
21             }
22         }
23     }
View Code

 

设计模式读书笔记-单件模式(创建型模式)

原文:http://www.cnblogs.com/dishiyicijinqiu/p/4617003.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!