Singleton 模式

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

namespace SingletonB
{
    //class SingletonB
    //{
    //    private static SingletonB instance;
    //    private SingletonB()
    //    {

    //    }
    //    public static SingletonB GetInstance()
    //    {
    //        if (instance == null)
    //        {
    //            instance = new SingletonB();
    //        }
    //        return instance;
    //    }
    //}
    //多线程Singleton.
    class SingletonB
    {
        private static SingletonB instance;
        private static readonly object syncObj = new object();
        private SingletonB()
        {

        }
        public static SingletonB GetInstance()
        {
            if (instance == null)
            {
                lock (syncObj)
                {
                    if (instance == null)
                    {
                        instance = new SingletonB();
                    }
                }
            }
            return instance;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            SingletonB s1 = SingletonB.GetInstance();
            SingletonB s2 = SingletonB.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("the same instance!");
            }
            Console.ReadLine();
        }
    }
}

//饿汉式Singleton

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();

    private Singleton()
    {

    }
    public static Singleton GetInstance()
    {
        return instance;
    }
}

原文地址:https://www.cnblogs.com/MayGarden/p/1516813.html