单件模式
2012-08-15 10:08
225 查看
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CountClient { public class CountSigleton { static CountSigleton uniCounter = null; private int totNum = 0; private CountSigleton() { Thread.Sleep(2000); } public static CountSigleton Instance { get { if (uniCounter==null) { uniCounter=new CountSigleton(); } return uniCounter; } } public void Add() { totNum++; } public int GetCounter() { return totNum; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace CountClient { public class CountMutilThread { public CountMutilThread(){ } public static void DoSomeWork() { string results = ""; 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(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CountClient { class Program { static void Main(string[] args) { CountMutilThread cmt = new CountMutilThread(); cmt.StartMain(); Console.ReadLine(); } } }
单件模式,例子。
保证一个类仅有一个实例
参考:http://terrylee.cnblogs.com/archive/2005/12/09/293509.html
相关文章推荐
- .net 单件模式(基类)
- 设计模式学习笔记(二)——Singleton单件模式
- 单件模式Singleton Pattern
- 【读书笔记】HeadFirst设计模式——单件不简单:详述实现Singleton模式需要考虑的方方面面
- 可继承的模板类单件模式
- .NET设计模式(2):单件模式(Singleton Pattern)
- 单件模式之土著人地可乐瓶
- 单件模式(Singleton)
- 设计模式——单件模式
- 设计模式初学者系列-单件模式
- 单件模式(Singleton Pattern)
- 从实例重温工厂模式和单件模式
- 单件模式(Singleton Pattern)
- 单件模式(Singleton Pattern)
- 系统架构技能之设计模式-单件模式 推荐
- 单件(单态,Singleton)模式部分
- 使用工厂模式和单件模式构建通用数据库访问类
- 单件模式
- 设计模式---单件(C++版) 希望大家顶一下
- 设计模式---单件(C++版) 比较通用的单件模式(STL实现)