c# 单例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Singleton
{
    public class SingletonTest
    {
        private static SingletonTest singleton;
        private static readonly object syncObject = new object();
        /// <summary>
        /// 构造函数必须是私有的
        /// 这样在外部便无法使用 new 来创建该类的实例
        /// </summary>
        private SingletonTest()
        { }
        /// <summary>
        /// 定义一个全局访问点
        /// 设置为静态方法
        /// 则在类的外部便无需实例化就可以调用该方法
        /// </summary>
        /// <returns></returns>
        public static SingletonTest getSingleton()
        {
            //这里可以保证只实例化一次
            //即在第一次调用时实例化
            //以后调用便不会再实例化
            //第一重 singleton == null
            if (singleton == null)
            {
                lock (syncObject)
                {
                    //第二重 singleton == null
                    if (singleton == null)
                    {
                        Console.WriteLine(String.Format("我是被线程:{0}创建的!", Thread.CurrentThread.Name));
                        singleton = new SingletonTest();
                    }
                }
            }
            return singleton;
        }
    }
}
原文地址:https://www.cnblogs.com/gaocong/p/6628064.html