Singleton Pattern 이란?
싱글톤 패턴이란 객체의 인스턴스가 오직 1개만 생성되는 패턴입니다.
즉, 런타임 동안 메모리에 오직 하나의 인스턴스만 존재하는 것을 의미합니다.
싱글톤 패턴의 주요 목적은 유일성을 보장하는 것입니다.
그러므로 일관되고 유일하며 전역적으로 접근할 수 있는 시스템을 관리하는 클래스에 사용할 경우 도움됩니다.
Singleton Pattern의 구성

- static 인스턴스를 생성하여 메모리에 할당해 둡니다.
- 생성되어 있는 인스턴스를 Client들이 접근합니다.
- 이미 인스턴스가 생성되어 있는 경우 같은 유형의 인스턴스가 발견되면 삭제합니다.
Singleton 구현
[Singleton Class]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| using UnityEngine;
public class Singleton <T> : MonoBehaviour where T : Component { private static T instance;
public static T Instance { get { if(instance == null) { instance = FindObjectOfType<T>(); if(instance == null) { GameObject obj = new GameObject(); obj.name = typeof(T).Name; instance = obj.AddComponent<T>(); } } return instance; } }
public virtual void Awake() { if(instance == null) { instance = this as T; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } }
|
[GameManager Class]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| using System; using UnityEngine; using UnityEngine.SceneManagement;
public class GameManager : Singleton<GameManager> { private DateTime _sessionStartTime; private DateTime _sessionEndTime;
void Start() { _sessionStartTime = DateTime.Now; Debug.Log($"Game session start: {DateTime.Now}"); }
private void OnApplicationQuit() { _sessionEndTime = DateTime.Now; TimeSpan timeDifference = _sessionEndTime.Subtract(_sessionStartTime); Debug.Log($"Game session ended: {DateTime.Now}"); Debug.Log($"Game session lasted: {timeDifference}"); }
private void OnGUI() { if(GUILayout.Button("Next Scene")) { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } } }
|
Singleton Pattern의 장단점
장점
- 시스템의 전역 접근점을 만들 수 있습니다.
- 메모리 자원 낭비를 방지할 수 있습니다.
단점
- 클래스 간의 의존성이 높아지게 됩니다.
- 접근하는 객체들을 추적하기가 어려워집니다.
- 결합도가 높아지므로 유닛 테스트가 힘들어집니다.