浅尝DesignPattern_Singleton

本文详细介绍了使用C#实现Singleton模式的方法,通过双重检查锁定确保线程安全的同时,也提供了延迟实例化的机制。该实现利用了静态构造函数和锁对象来创建一个单一实例。

 Singleton

-------------------------------------------------------------------------------------------------------

 UML:

2010041902125230.png

--------------------------------------------------------------------------------------------------------

SAMPLE:

 

1 class SingletonClient
2 {
3 static void Main(string[] args)
4 {
5 Singleton singleton = Singleton.getInstance();
6 singleton.SaySomething();
7
8 // Wait for user
9   Console.ReadKey();
10 }
11 }
12
13 #region Singleton
14
15 public class Singleton
16 {
17 private volatile static Singleton _uniqueInstance;
18 private static readonly object _syncLock = new object();
19
20 private Singleton() {}
21
22 public static Singleton getInstance()
23 {
24 if (_uniqueInstance == null)
25 {
26 // Lock area where instance is created
27   lock(_syncLock)
28 {
29 if (_uniqueInstance == null)
30 {
31 _uniqueInstance = new Singleton();
32 }
33 }
34 }
35 return _uniqueInstance;
36 }
37
38 public void SaySomething()
39 {
40 Console.WriteLine("I am double checked, therefore I am");
41 }
42 }

 

 

 

转载于:https://www.cnblogs.com/TivonStone/archive/2010/04/19/1715077.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值