写这个系列的文章,只为把所学的设计模式再系统的整理一遍。错误和不周到的地方欢迎大家批评。点击这里下载源代码。

什么时候使用单例模式

在程序运行时,某种类型只需要一个实例时,一般采用单例模式。为什么需要一个实例?第一,性能,第二,保持代码简洁,比如程序中通过某个配置类A读取配置文件,如果在每处使用的地方都new A(),才能读取配置项,一个是浪费系统资源(参考.NET垃圾回收机制),再者重复代码太多。

单例模式的实现

实现单例模式,方法非常多,这里我把见过的方式都过一遍,来体会如何在支持并发访问、性能、代码简洁程度等方面不断追求极致。(单击此处下载代码)

实现1:非线程安全

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
   7:  
namespace SingletonPatternNotTheadSafe
   9: {
class Singleton
  11:     {
null;
  13:  
private Singleton()
  15:         {
  16:         }
  17:  
static Singleton Instance
  19:         {
  20:             get
  21:             {
null)
  23:                 {
  24:                     Thread.Sleep(1000);
new Singleton();
string.Format(
 , Thread.CurrentThread.ManagedThreadId, instance.GetHashCode()));
  28:                 }
  29:  
string.Format(
, Thread.CurrentThread.ManagedThreadId, instance.GetHashCode()));
return instance;
  33:             }
  34:         }
  35:     }
  36: }

相关文章: