개인 이해의 단례 모델

5907 단어 단일 모드
다음은 개인이 이해할 수 있는 단일 예제 모델입니다.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace ConsoleApplication6

{

  public  sealed class Singleton

    {

      static Singleton instance;

      /// <summary>

      ////// </summary>

      private Singleton() { }

      public static Singleton Instance 

      {

          get 

          {

              return instance == null ? new Singleton() : instance;

          }

      }

      public void dd(){

          Console.WriteLine("fdd");

          Console.ReadLine();

      }

     

    }

}

주 메서드는 다음과 같이 호출됩니다.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace ConsoleApplication6

{

    class Program

    {

        static void Main(string[] args)

        {

            Singleton.Instance.dd();

          

            

        }

    }

}

물론 이것은 때때로 단례가 유일하다는 것을 보장할 수 없으며, lock 방법으로 다음과 같이 실현할 수 있다.
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;



namespace ConsoleApplication6

{

    public sealed class Singleton

    {

        static Singleton instance;

        static readonly object padlock = new object();

      

        public Singleton() { }

        public static Singleton Instance

        {



            get

            {

                if (instance == null)

                {

                    lock (padlock)

                    {

                        if (instance == null) 

                        {

                            instance=new Singleton() ;

                        }

                        

                    }

                   

                }

                return instance;

            }

        }

        public void dd()

        {

            Console.WriteLine("fdd");

            Console.ReadLine();

        }



    }

}

환영하다

좋은 웹페이지 즐겨찾기