C# 单例模式

1.懒汉模式(延时加载,他是在需要的时候才创建对象) 

 1 public class Singleton
 2 {
 3         private static Singleton _Singleton = null;
 4         private static object Singleton_Lock = new object();
 5         public static Singleton CreateInstance()
 6         {
 7             //Singleton _Singleton = null;
 8             if (_Singleton == null)//对象初始化之后,不要再等待锁了
 9             {
10                 lock (Singleton_Lock)//保证lock的方法体同一时刻只有一个线程可以进入
11                 {
12                     if (_Singleton == null)//是保证第一次初始化之后,不再重复的初始化
13                     {
14                         _Singleton = new Singleton();
15                     }
16                 }
17             }
18             return _Singleton;
19         }
20 }

2.饿汉模式

1  public class Singleton
2     {
3         private static Singleton _Singleton = new Singleton();//加载类即实例化
4 
5         public static Singleton CreateInstance()
6         {
7             return _Singleton;
8         }
9 }
public class Singleton
{
        private static Singleton _Singleton = null;
        static Singleton()//类加载执行静态构造函数
        {
            _Singleton = new Singleton();
        }

        public static Singleton CreateInstance()
        {
            return _Singleton;
        }
}

懒汉和饿汉的本质区别,就是实例化对象的时机,饿汉即类加载就会实例化对象,懒汉则是使用时才会实例化

原文地址:https://www.cnblogs.com/huierz/p/7327275.html