1、Singleton模式(创建型)A class of which only a single instance can exist
单线程:
//lazy load public class Singleton { private static Singleton instance; private Singleton{} publist static Singleton Instance { get{return instance == null ?new Singleton():instance;} } //thread not safe } //immdiately load public class Singleton { private static Singleton instance = new Singleton(); private Singleton{} publist static Singleton Instance { get{return instance;} } publist static Singleton GetInstance()//C#中实现同一个目的,实现方法太多了!!! { return instance; } //thread not safe }
多线程:
//lazy load public class Singleton { private static Singleton instance; private static object lockHelper = new Object(); private Singleton{} public static Singleton Instance { get{ if(instance == null) { lock(lockHelper)//avoid multi-thread { if(instance == null)//double check instance = new Singleton(); } } return instance; } } //thread not safe }
.NET optimized code //单、多通吃
public sealed class Singleton { // Static members are 'eagerly initialized', that is, // immediately when class is loaded for the first time. // .NET guarantees thread safety for static initialization private static readonly Singleton _instance = new Singleton(); private Singleton(){} }
使用泛型,做个Provider
代码
public class SingletonProvider<T> where T : new()
{
SingletonProvider() { }
public static T Instance
{
get { return SingletonCreator.instance; }
}
class SingletonCreator
{
static SingletonCreator() { }
internal static readonly T instance = new T();
}
}
动机(Motivation)
1、在软件系统中,经常有这样一些特殊的类,必须保证它们在系统中只存在一个实例,才能确保它们的逻辑正确性、以及良好的效率。
2、如何绕过常规的构造器,提供一种机制来保证一个类只有一个实例?
3、这应该是类设计者的责任,而不是使用者的责任。
意图(Intent)
保证一个类仅有一个实例,并提供一个该实例的全局访问点。——《设计模式》GoF
Singleton模式扩展
• 将一个实例扩展到n个实例,例如对象池的实现。
• 将new 构造器的调用转移到其他类中,例如多个类协同工作环境中,某个局部环境只需要拥有某个类的一个实例。
• 理解和扩展Singleton模式的核心是“如何控制用户使用new对一个类的实例构造器的任意调用”。
不错的参考:
http://www.dofactory.com/Patterns/PatternSingleton.aspx
http://www.cnblogs.com/webabcd/archive/2007/02/10/647140.html