单例模式

using System;

namespace 设计模式_单例模式
{
class Program
{
///


/// 单例模式(不适应与多线程)
///

public class Singleton
{
private static Singleton insrence;

        private Singleton() { }

        public  static Singleton Instence
        {
            get 
            { 
                if (insrence==null)
                {
                    insrence = new Singleton(); 
                }
                return insrence;
            }
        }
    }
    
    /// <summary>
    /// 适用于多线程
    /// </summary>
    public class SingletonTrs
    {
        private static volatile SingletonTrs instence;//volatile:保证代码编译后严格按照此执行顺序

        private static object lockHelper = new object();
        private SingletonTrs() { }

        public static SingletonTrs Instence
        {
            get
            {
                //双重检查-多线程访问时保证只生成一个单例
                if (instence == null)
                {
                    lock (lockHelper)
                    {
                        if (instence == null)
                        {
                            instence = new SingletonTrs();
                        }
                    }
                }
                return instence;
            }

        }
    }
    /// <summary>
    /// 适用于多线程
    /// </summary>
    class Singleton3
    {
        public static readonly Singleton3 Instence = new Singleton3();//内联初始化
        private Singleton3() { }
    }
    /// <summary>
    /// 同上
    /// </summary>
    class Singletog33
    {
        public static readonly Singletog33 Instence;

        static Singletog33()//放在静态构造器,先于静态属性执行(只会被一个线程执行) 缺点:无法传递参数
        {
            Instence = new Singletog33();
        }
        private Singletog33() { }
    }

    static void Main(string[] args)
    {
        
    }
}

}