1、饿汉式单例模式
// 饿汉式单例模式 - by Chimomo namespace CSharpLearning { public sealed class Singleton { private static readonly Singleton instance = new Singleton(); private Singleton() { } public static Singleton Instance { get { return instance; } } } }
2、懒汉式单例模式
2.1、借助内部类
// 懒汉式单例模式:借助内部类 - by Chimomo namespace CSharpLearning { public sealed class Singleton { private Singleton() { } private static class SingletonHolder { public static readonly Singleton instance = new Singleton(); } public static Singleton Instance { get { return SingletonHolder.instance; } } } }2.2、普通加锁
// 懒汉式单例模式:普通加锁 - by Chimomo namespace CSharpLearning { public sealed class Singleton { private static volatile Singleton instance; private static readonly object syncRoot = new object(); private Singleton() { } public static Singleton Instance { get { lock (syncRoot) { if (instance == null) { instance = new Singleton(); } } return instance; } } } }2.3、双重检测加锁
// 懒汉式单例模式:双重检测加锁 - by Chimomo namespace CSharpLearning { public sealed class Singleton { private static volatile Singleton instance; private static readonly object syncRoot = new object(); private Singleton() { } public static Singleton Instance { get { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new Singleton(); } } } return instance; } } } }
原文地址:http://blog.csdn.net/troubleshooter/article/details/41480349