单例模式
单例模式(Singleton):
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
一、UML结构图
二、示例代码【重点】
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace 单例模式 7 { 8 class Program 9 { 10 static void Main(string[] args) 11 { 12 SingleModelOne.GetInstance().Show(); 13 SingleModelTwo.GetInstance().Show(); 14 SingleModelThree.GetInstance().Show(); 15 16 Console.Read(); 17 } 18 } 19 20 /// <summary> 21 /// 单线程单例模式(懒汉式单例) 22 /// </summary> 23 public class SingleModelOne 24 { 25 private static SingleModelOne m_SingleModeOne = null; 26 27 /// <summary> 28 /// 单例模式的构造函数一定要【私有化】 29 /// </summary> 30 private SingleModelOne() { } 31 32 public static SingleModelOne GetInstance() 33 { 34 if (m_SingleModeOne == null) 35 m_SingleModeOne = new SingleModelOne(); 36 37 return m_SingleModeOne; 38 } 39 public void Show() 40 { 41 Console.WriteLine("1、我是懒汉式、单线程单例模式"); 42 } 43 } 44 45 /// <summary> 46 /// 多线程单例模式(懒汉式单例) 47 /// </summary> 48 public class SingleModelTwo 49 { 50 private static SingleModelTwo m_SingleModeTwo = null; 51 private static object m_LockObj = new object(); 52 53 /// <summary> 54 /// 单例模式的构造函数一定要【私有化】 55 /// </summary> 56 private SingleModelTwo() { } 57 58 public static SingleModelTwo GetInstance() 59 { 60 //双重加锁 一 :是为了防止线程阻塞,若对象已创建,此时在lock内部判断,就会导致其它线程在lock外等待。 61 if (m_SingleModeTwo == null) 62 { 63 lock (m_LockObj) 64 { 65 if (m_SingleModeTwo == null) 66 m_SingleModeTwo = new SingleModelTwo(); 67 } 68 } 69 return m_SingleModeTwo; 70 } 71 public void Show() 72 { 73 Console.WriteLine("2、我是懒汉式、多线程单例模式"); 74 } 75 } 76 77 /// <summary> 78 /// 单线程单例模式(饿汉式单例) 79 /// 饿汉式:【sealed】防止类被派生,派生就可能会增加实例。 80 /// 【readonly】对象只读,交由OCL负责初始化变量 81 /// </summary> 82 public sealed class SingleModelThree 83 { 84 //首先将对象初始化完毕 85 private readonly static SingleModelThree m_SingleModelThree = new SingleModelThree(); 86 87 /// <summary> 88 /// 单例模式的构造函数一定要【私有化】 89 /// </summary> 90 private SingleModelThree() { } 91 92 public static SingleModelThree GetInstance() 93 { 94 return m_SingleModelThree; 95 } 96 public void Show() 97 { 98 Console.WriteLine("3、我是饿汉式、单线程单例模式"); 99 } 100 } 101 102 }