设计模式(一) :单例模式
单例模式(Singleton Pattern)是最简单的设计模式之一。它保证一个类仅有一个实例,并提供一个访问它的全局访问点
单例模式的实现可以分为饿汉模式和懒汉模式
饿汉单例模式
/// <summary> /// 饿汉单例模式 提前初始化对象 /// </summary> public class SingletonA { /// <summary> /// 提前初始化实例 /// </summary> private static SingletonA _singleton = new SingletonA(); /// <summary> /// 私有化构造函数 /// </summary> private SingletonA() { } /// <summary> /// Get Singleton Instance /// </summary> /// <returns></returns> public static SingletonA GetInstance() { return _singleton; } /// <summary> /// do something /// </summary> public void PrintMsg() { Console.WriteLine(this.GetHashCode()); } }
懒汉单例模式(双重检查加锁机制)
/// <summary> /// 懒汉单例模式 使用时再初始化对象 /// </summary> public class SingletonB { private static SingletonB _singleton = null; private static object locker = new object(); /// <summary> /// 私有化构造函数 /// </summary> private SingletonB() { } /// <summary> /// Get Singleton Instance /// </summary> /// <returns></returns> public static SingletonB GetInstance() { //双重检查加锁机制 if (_singleton == null) { lock (locker) { if (_singleton == null) { _singleton = new SingletonB(); } } } return _singleton; } /// <summary> /// do something /// </summary> public void PrintMsg() { Console.WriteLine(this.GetHashCode()); } }