본문 바로가기
프로그래밍/C#

C# 싱글톤 패턴 예제 모음

by zoo10 2018. 2. 21.



멀티스레드에 안전하지 않은 싱글톤 패턴


using System;


public class Singleton

{

   private static Singleton instance;


   private Singleton() {}


   public static Singleton Instance

   {

      get 

      {

         if (instance == null)

         {

            instance = new Singleton();

         }

         return instance;

      }

   }

}



멀티스레드에 안전한 싱글톤 패턴


public sealed class Singleton

{

    private static Singleton instance = null;

    private static readonly object padlock = new object();


    Singleton()

    {

    }


    public static Singleton Instance

    {

        get

        {

            lock (padlock)

            {

                if (instance == null)

                {

                    instance = new Singleton();

                }

                return instance;

            }

        }

    }

}


.NET 4.x 버전 Lazy<T>를 이용한 싱글톤

public sealed class Singleton

{

    private static readonly Lazy<Singleton> lazy =

        new Lazy<Singleton>(() => new Singleton());

    

    public static Singleton Instance { get { return lazy.Value; } }


    private Singleton()

    {

    }

}



출처 : https://msdn.microsoft.com/en-us/library/ff650316.aspx

출처 : http://csharpindepth.com/Articles/General/Singleton.aspx