单例模式
Posted zhuyapeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单例模式相关的知识,希望对你有一定的参考价值。
三种实现单例的方式
主测试代码:
class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { Task task = Task.Factory.StartNew(() => { //Single s = Single.CreateSingle(); //Single_2 s = Single_2.CreateSingle(); Single_3 s = Single_3.instance; s.Say(); }); } Console.ReadKey(); } }
第一种:
/// <summary> /// 简单写法:会出现线程安全问题 /// </summary> public class Single { private static Single _single = null; static object obj = new object(); private Single() { } public static Single CreateSingle() { if (_single==null) { Console.WriteLine("对象被初始化--{0}",System.Threading.Thread.CurrentThread.ManagedThreadId); _single = new Single(); } return _single; } public void Say() { Console.WriteLine("执行say方法--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId); } }
第二种:
/// <summary> /// 安全写法,加入锁 /// </summary> public class Single_2 { private static Single_2 _single = null; static object obj = new object(); private Single_2() { } public static Single_2 CreateSingle() { if (_single == null) { lock (obj) { if (_single == null) { Console.WriteLine("对象被初始化--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId); _single = new Single_2(); } } } return _single; } public void Say() { Console.WriteLine("执行say方法--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId); } }
第三种:
/// <summary> /// 精简写法 /// </summary> public class Single_3 { public static readonly Single_3 instance = new Single_3(); private Single_3() { Console.WriteLine("对象被初始化--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId); } public void Say() { Console.WriteLine("执行say方法--{0}", System.Threading.Thread.CurrentThread.ManagedThreadId); } }
以上是关于单例模式的主要内容,如果未能解决你的问题,请参考以下文章