首页 > 其他 > 详细

单例模式

时间:2021-06-25 12:24:42      阅读:8      评论:0      收藏:0      [点我收藏+]
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace DesignPattern.CreationalPatern
 8 {
 9     //定义 1.只能创建一个实例 2.提供一个全局访问
10 
11     public class SingletonPattern
12     {
13         private static SingletonPattern _singletonMode = null;
14         private static readonly object _objLock = new object();
15         private SingletonPattern() { }
16 
17         //双重锁定,防止多线程的资源浪费
18         public static SingletonPattern Instance() 
19         {
20             //判断是否已有实例,避免重复执行加锁操作,会消耗CPU资源,涉及到线程上线文切换
21             if (_singletonMode != null)
22             {
23                 //混合状态锁,锁对象一定要是用引用类型,因引用类型包含两个指针,TypeHandler和同步块索引(指向同步块实际意义上的锁)
24                 //锁对象不能使用字符串,字符串具有驻留性,可能多个AppDomin都会用到
25                 lock (_objLock)
26                 {
27                     if (_singletonMode != null)
28                     {
29                         _singletonMode = new SingletonPattern();
30                     }
31                 }
32             }
33 
34             return _singletonMode;
35         }
36     }
37 }
38  

 

单例模式

原文:https://www.cnblogs.com/howiego/p/SingletonPattern.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!