您的位置:首页 > 其它

SingleTon 要求一个类有且仅有一个实例,并提供一个全局的访问点.

2006-12-31 09:50 393 查看
using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace Gof.Nan.Test
6 Gof.Nan.Test.SingleTon s1, s2;
2 s1 = Gof.Nan.Test.SingleTon.CreateInstance();
3 s2 = Gof.Nan.Test.SingleTon.CreateInstance();
4 if (s1.Equals(s2))
5using System;
2using System.Collections.Generic;
3using System.Text;
4
5namespace Gof.Nan.Test
6{
7 class SingleTonInMultiThread
8 {
9 private static SingleTonInMultiThread _singleTon;
10 private static object _classLock = typeof(SingleTon);
11 private long _wipMoves;//私有变量,表示一定的意义.
12 private SingleTonInMultiThread(){
13 _wipMoves = 0;
14 }
15 public SingleTonInMultiThread CreateInstance()
16 {
17 lock (_classLock)
18 {
19 if (_singleTon == null)
20 {
21 _singleTon = new SingleTonInMultiThread();
22 }
23 return _singleTon;
24 }
25 }
26 public void DoSomething()
27 {
28 lock (_classLock)//保证其在执行时的线程安全性
29 {
30 _wipMoves++;
31 }
32 }
33 }
34}

The Singleton Pattern ensures a class has oly one instance, and provides a global point of access to it.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐