本文将会介绍设计模式中最简单,最常用的一种模式 -> 单例模式
什么是单例模式?
单例模式属于创建型模式,顾名思义,单例模式重点在于怎么在一个程序中保持只有一个实例。
- 单例模式下的类型只能有一个实例
- 必须提供创建自己创建自身的方法
- 必须对外提供访问唯一实例的方法
关键点:私有化构造函数
例如一个全局的程序缓存的单例实现的UML图
代码实现
namespace DM
{
using System;
using System.Threading;
class AppCache
{
private static Object _lockForInstance = new Object();
private static AppCache _instance = null;
public static AppCache Instance
{
get
{
if (_instance != null) return _instance;
Boolean lockTaken = false;
Monitor.Enter(_lockForInstance, ref lockTaken);
try
{
if(_instance == null)
{
var tmp = new AppCache();
Volatile.Write(ref _instance, tmp);
}
}
finally
{
if (lockTaken) Monitor.Exit(_lockForInstance);
}
return _instance;
}
}
private AppCache()
{
// Init SomeThing...
}
}
}