设计模式-单例模式
感觉程序员熟悉设计模式还是比较必要的,把自己的学习笔记整理一下,大家可以做个参考,相互促进!
首先是单例模式,个人理解就是控制使用者不能new出新实例,而是通过方法得到一个唯一的实例。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SingletonPattern
{
class Program
{
static void Main(string[] args)
{
CountMutilThread cmt = new CountMutilThread();
cmt.StartMain();
Console.ReadLine();
}
}
/// <summary>
/// 功能:创建一个多线程计数的类
/// 编写:Terrylee
/// 日期:2005年12月06日
/// </summary>
public class CountMutilThread
{
public CountMutilThread()
{
}
/// <summary>
/// 线程工作
/// </summary>
public static void DoSomeWork()
{
///构造显示字符串
string results = "";
///创建一个Sigleton实例
CountSigleton MyCounter = CountSigleton.Instance();
///循环调用四次
for(int i=1;i<5;i++)
{
///开始计数
MyCounter.Add();
results +="线程";
results += Thread.CurrentThread.Name.ToString() + "——〉";
results += "当前的计数:";
results += MyCounter.GetCounter().ToString();
results += "\n";
Console.WriteLine(results);
///清空显示字符串
results = "";
}
}
public void StartMain()
{
Thread thread0 = Thread.CurrentThread;
thread0.Name = "Thread 0";
Thread thread1 =new Thread(new ThreadStart(DoSomeWork));
thread1.Name = "Thread 1";
Thread thread2 =new Thread(new ThreadStart(DoSomeWork));
thread2.Name = "Thread 2";
Thread thread3 =new Thread(new ThreadStart(DoSomeWork));
thread3.Name = "Thread 3";
thread1.Start();
thread2.Start();
thread3.Start();
///线程0也只执行和其他线程相同的工作
DoSomeWork();
}
}
}
/// <summary>
/// 功能:简单计数器的单件模式
/// 编写:Terrylee
/// 日期:2005年12月06日
/// </summary>
public class CountSigleton
{
///存储唯一的实例
static CountSigleton uniCounter = new CountSigleton();
///存储计数值
private int totNum = 0;
private CountSigleton()
{
///线程延迟2000毫秒
Thread.Sleep(2000);
}
static public CountSigleton Instance()
{
return uniCounter;
}
///计数加1
public void Add()
{
totNum ++;
}
///获得当前计数值
public int GetCounter()
{
return totNum;
}
}

通过运行结果,我们可以得到很多有用的信息,不仅仅是单例模式,还有对多线程一些知识的验证,例如线程的执行顺序。
最后:本文是根据TerryLee's Tech Space博客写出来的,理解能力有限,如有不明白的,可以去看原稿!
http://www.cnblogs.com/Terrylee/archive/2005/12/09/293509.html
浙公网安备 33010602011771号