STUDY/Design Pattern

단일체 패턴(Singleton Pattern)

디리릭 2022. 11. 27. 20:50
728x90

단일체 패턴(싱글톤)은 프로그램에서 특정 객체가 단 하나 생성할 수 있는 패턴이다.

객체가 하나만 생성되므로 여러개의 인스턴스를 생성했을 때의 메모리 낭비를 방지할 수 있다. 또 싱글톤으로 만들어진 클래스의 인스턴스는 전역 인스턴스이기 때문에 다른 클래스에서 접근하기 쉽다. 그러기 때문에 쓰레드풀, 캐시, 사용자 설정, 로그 기록 등에 많이 사용 된다.

구조

▷Singleton : 메모리에 항상 영역을 잡는 클래스 생성

구현

    class Singleton
    {
        private static Singleton singleton;
        public static Singleton instance() 
        {
            if (singleton == null) 
            {
                singleton = new Singleton();
            }
            return singleton;
        }
        public void log(string logString) 
        {
            Console.WriteLine($"{logString}");
        }
    }
  static void Main(string[] args)
        {
          

            for (int i = 0; i < 10; i++)
            {
                var singleton = Singleton.instance();
                var singleton1 = Singleton.instance();
                if (singleton == singleton1) 
                {
                    singleton.log(singleton.ToString() +" "+ i);
                }
         
            }
            Console.Read();
        }

결과 >>>>>>

Singleton에서 instance는 static으로 생성했기 때문에 객체 생성할 때 new 를 사용하지 않아도 된다.

singleton, singleton1 을 생성하여 2개의 객체인것 처럼 보이지만 이 두 객체의 주소는 같다는걸 알 수 있다.

그러므로 두 객체는 같은 주소를 같는 Singleton에 대한 객체임을 알 수 있다.

Singleton의 단점은 결합도를 높일 수 있다.

M(VVM) <- 싱글톤이 쓰임

C#에서는 아래와 같이 싱글톤을 사용할 수도 있다.

  public class StaticUtils
    {
        private static Lazy<StaticUtils> _instance = new Lazy<StaticUtils>(()=>new StaticUtils());

        public StaticUtils getInstance
        {
            get => _instance.Value;
        }
    }
728x90