개인 공부/디자인패턴

디자인패턴 싱글톤

smallship 2024. 7. 12. 20:44

디자인패턴 : 싱글톤

단 한개의 객체만 존재하며 여러 오브젝트가 접근을 해야 하는 스크립트의 역할을 한다.

새로운 씬을 로드하게 되면 기존것들이 파괴되게 되는데 싱글톤을 사용하면 씬 로드시 데이터가 파괴되지 않고 유지된다.

 

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

// 씬 내에 오브젝트를 바인딩 하지 않는 구조이면서
// 데이터를 다른 씬으로 넘어가도 누적되서 사용해야 하거나
// 씬 로드와는 상관없이 사용해야 하는 경우에서
// DontDesrtoyOnLoad를 통해서 삭제되지 않게 한다.
public class Singleton_immortal : MonoBehaviour
{
    private static Singleton_immortal _instance;

    public static Singleton_immortal Instance
    {
        get
        {
            if (_instance == null)

            {
                _instance = FindObjectOfType<Singleton_immortal>();

                if (_instance == null)
                {
                    GameObject singletonPrefab = Resources.Load("Singleton") as GameObject;
                    GameObject singletonInstance = Instantiate(singletonPrefab);
                    if (singletonInstance != null) _instance = singletonInstance.GetComponent<Singleton_immortal>();
                }
            }

            return _instance;
        }
    }

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

    public void TestFunc()
    {
        Debug.Log("TestFunction");
    }
}

Singleton_immortal 스크립트를 작성하고

Resource 폴더 안에 프리팹을 만들어 적용시켜준다.

 

 

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

public class SingletonUsing : MonoBehaviour
{
    public Singleton_immortal _Singleton;
    // Start is called before the first frame update
    void Start()
    {
        _Singleton=Singleton_immortal.Instance;
    }

    // Update is called once per frame
    void Update()
    {
        _Singleton.TestFunc();
    }
}

SingletonUsing 스크립트를 작성하고 

하이라키창에 빈 오브젝트 생성 후 해당 스크립트를 삽입해준다.

 

실행하면 로그가 잘 출력되고 삭제되지 않는 오브젝트가 생성되는것을 확인할 수 있다.

 

싱글톤은 접근이 쉽게 가능하지만 하나의 싱글톤에 많은 기능을 넣으면 규모가 커지게 되고 메모리를 지속해서 유지하기 때문에 메모리가 비효율적으로 사용되게 된다.

따라서 싱글톤을 사용하되 자신이 컨트롤 할 수 있는 수준에서 사용해야 한다.

'개인 공부 > 디자인패턴' 카테고리의 다른 글

디자인패턴 데코레이터  (0) 2024.07.15
디자인패턴 브릿지  (0) 2024.07.15
디자인패턴 프로토타입  (0) 2024.07.12
디자인패턴 빌더  (1) 2024.07.12
디자인패턴 추상팩토리  (2) 2024.07.12