这是一个简单的计数器例子,四个线程同时进行计数。
1using System;
2using System.Threading;
3
4namespace SigletonPattern.SigletonCounter
5{
6 /**//// <summary>
7 /// 功能:简单计数器的单件模式
8 /// 编写:Terrylee
9 /// 日期:2005年12月06日
10 /// </summary>
11 public class CountSigleton
12 {
13 /**////存储唯一的实例
14 static CountSigleton uniCounter = new CountSigleton();
15
16 /**////存储计数值
17 private int totNum = 0;
18
19 private CountSigleton()
20
21 {
22 /**////线程延迟2000毫秒
23 Thread.Sleep(2000);
24 }
25
26 static public CountSigleton Instance()
27
28 {
29
30 return uniCounter;
31
32 }
33
34 /**////计数加1
35 public void Add()
36 {
37 totNum ++;
38 }
39
40 /**////获得当前计数值
41 public int GetCounter()
42 {
43 return totNum;
44 }
45
46 }
47}
48
1using System;
2using System.Threading;
3using System.Text;
4
5namespace SigletonPattern.SigletonCounter
6{
7 /**//// <summary>
8 /// 功能:创建一个多线程计数的类
9 /// 编写:Terrylee
10 /// 日期:2005年12月06日
11 /// </summary>
12 public class CountMutilThread
13 {
14 public CountMutilThread()
15 {
16
17 }
18
19 /**//// <summary>
20 /// 线程工作
21 /// </summary>
22 public static void DoSomeWork()
23 {
24 /**////构造显示字符串
25 string results = "";
26
27 /**////创建一个Sigleton实例
28 CountSigleton MyCounter = CountSigleton.Instance();
29
30 /**////循环调用四次
31 for(int i=1;i<5;i++)
32 {
33 /**////开始计数
34 MyCounter.Add();
35
36 results +="线程";
37 results += Thread.CurrentThread.Name.ToString() + "——〉";
38 results += "当前的计数:";
39 results += MyCounter.GetCounter().ToString();
40 results += "\n";
41
42 Console.WriteLine(results);
43
44 /**////清空显示字符串
45 results = "";
46 }
47 }
48
49 public void StartMain()
50 {
51
52 Thread thread0 = Thread.CurrentThread;
53
54 thread0.Name = "Thread 0";
55
56 Thread thread1 =new Thread(new ThreadStart(DoSomeWork));
57
58 thread1.Name = "Thread 1";
59
60 Thread thread2 =new Thread(new ThreadStart(DoSomeWork));
61
62 thread2.Name = "Thread 2";
63
64 Thread thread3 =new Thread(new ThreadStart(DoSomeWork));
65
66 thread3.Name = "Thread 3";
67
68 thread1.Start();
69
70 thread2.Start();
71
72 thread3.Start();
73
74 /**////线程0也只执行和其他线程相同的工作
75 DoSomeWork();
76 }
77 }
78}
79
总结1using System;
2using System.Text;
3using System.Threading;
4
5namespace SigletonPattern.SigletonCounter
6{
7 /**//// <summary>
8 /// 功能:实现多线程计数器的客户端
9 /// 编写:Terrylee
10 /// 日期:2005年12月06日
11 /// </summary>
12 public class CountClient
13 {
14 public static void Main(string[] args)
15 {
16 CountMutilThread cmt = new CountMutilThread();
17
18 cmt.StartMain();
19
20 Console.ReadLine();
21 }
22 }
23}
24
Singleton设计模式是一个非常有用的机制,可用于在面向对象的应用程序中提供单个访问点。文中通过五种实现方式的比较和一个完整的示例,完成了对Singleton模式的一个总结和探索。用一句广告词来概括Singleton模式就是“简约而不简单”。
源码下载:/Files/Terrylee/SigletonPattern.rar
参考文献:
《C#计模式》,中国电力出版社
使用 Microsoft .NET 的企业解决方案模式
《Implementing the Singleton Pattern in C#》
MSDN《Exploring the Singleton Design Pattern》
吕震宇C#设计模式(7)-Singleton Pattern
C#的Singleton设计模式
