C# - 싱글톤패턴

Claire·2024년 11월 1일

싱글톤 패턴

싱글톤 패턴이란

특정 클래스의 인스턴스를 1개만 생성하도록 제한하고, 이를 공유하는 방법

생성자를 private으로 하고, 자기 자신을 받는 함수를 만들어서 자기 자신의 객체를 반환하는 클래스

싱글톤 패턴의 필요성

프로그램 내 특정 클래스 내에서 하나의 객체만 생성하고자 할 때 사용하며, 환경 설정 객체와 같이 공통으로 사용해야하는 모듈에서 사용한다.

정적 싱글톤

class SingletonClass
{
private:
	static SingletonClass instance;
    SingletonClass() {}
    ~SingletonClass() {}
public:
	static SingletonClass& getInstance()
    {
    	return Instance;
    }
};

SingletonClass SingletonClass::Instance;

생성자가 private인 이유는 외부에서 객체 생성을 막기 위함이고, 어디서든 싱글톤 객체를 접근할 수 있게 하기 위해서 static 함수를 정의하였다.

동적 싱글톤

class SingletonClass
{
private:
	static SingletonClass* instance;
    Singletonclass() {}
public:
	~Singletonclass() {}
    static SingletonClass *getInstance()
    {
    	if(instance == NULL)
        	instance = new SingletonClass();
        return Instance;
    }
};

함수 내에서 new 연산자로 static SingletonClass 객체를 생성할 때. instance의 생성 여부를 판단하는 NULL 체크 필수

동적 싱글톤 패턴의 문제점
new연산자를 통해 동적으로 생성한 객체에 대해 소멸을 보장받지 못하고, 이로 인해 메모리 누수가 발생한다. 따라서, 이러한 문제를 해결하기 위해 프로그램 종료 직전 소멸 루틴을 직접 호출해주어야 한다.

싱글톤 패턴(C# 예시 코드)

namespace 싱글톤패턴1
{
    class Singleton
    {
        private static Singleton instance;
        public static Singleton getInstance()
        {
            if(instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
        public void showMsg()
        {
            Console.WriteLine("싱글톤 패턴");
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Singleton instance = Singleton.getInstance();
            instance.showMsg();
        }
    }
}
profile
SEO 최적화 마크업 개발자입니다.

0개의 댓글