首页 > 代码库 > 单例模式
单例模式
三种实现单例的方式
主测试代码:
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); } }
单例模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。