싱글톤 패턴 (Singleton Pattern)

 

싱글톤 패턴은 소프트웨어 설계 패턴 중 하나로, 특정 클래스의 인스턴스가 하나만 만들어지고,

그 인스턴스로부터 통제되도록 보장하는 패턴이다.

 

즉,  전역 변수를 사용하지 않고도 객체가 전역적으로 접근 가능하도록 해준다.

싱글톤 패턴은 로그 파일 작성기, 데이터베이스 연결, 프린터 스풀러 등 공유 리소스에 대한 동시 접근을 제한하거나 한 번만 생성해야 하는 인스턴스를 제어할 때 주로 사용된다.

 
<C#의 싱글톤 패턴 예시>

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

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }
}




<유니티의 싱글톤 패턴 예시>

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    public int sumApple = 0;
    public int sumBomb = 0;
    public int sumScore = 0;

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            Destroy(gameObject);
        }
    }
}

mono 상속

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DownLoadManager
{
    private static DownLoadManager instance;


    public static DownLoadManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new DownLoadManager();
            }
            return instance;
        }
    }

    // 생성자를 private으로 만들어 외부에서 인스턴스를 생성하지 못하게 함
    private DownLoadManager() { }
}

비 mono 상속


Singleton 클래스의 생성자는 private로 선언되어 외부에서 직접 인스턴스를 생성할 수 없다.


또한 Singleton 인스턴스는 private static readonly 필드인 instance를 통해 생성되며,

Instance 프로퍼티를 통해 이 인스턴스에 접근할 수 있다.

 

 

 

+ Recent posts