겨울팥죽 여름빙수

 프로그래밍을 하다보면 가장 많이 쓰이는 것이 아마 싱글톤 패턴 일 것이다. 싱글톤을 만드는 방법은 다양한데, 클래스마다 그것을 구현 해 주기는 귀찮다. Java같은 경우 Enum타입으로 만들면 싱클톤이 되어서 편한데, c#같은 경우에는 그런 방법이 되지 않는다. 그나마 편하게 싱글톤 클래스를 만들고 사용하기 위한 방법은 제네릭을 이용하는 것이다.

 

1. c# 제네릭 싱클톤 클래스

using System;

public class Singleton<T> where T : Singleton<T>, new()
{  
    static T mInstnace;
    public static T Instance  
    {  
        get
        {
            if(mInstnace == null)
            {
                mInstnace = new T();
                mInstnace.init();
            }

            return mInstnace;
        }
    }  

    protected virtual void init()
    {

    }
} 

 

2. 사용 예

using System;
using System.Collections.Generic;


public class TextManager : Singleton<TextManager>
{
    Dictionary<string, jdText> m_text_map = new Dictionary<string, jdText>();

    public TextManager()
    {
    }


    override protected void init()
    {
    }

    public void AddText(jdText text)
    {
        if (!m_text_map.ContainsKey(text.text_key))
            m_text_map[text.text_key] = text;
    }

    public string GetText(string key)
    {
        if (m_text_map.ContainsKey(key))
            return m_text_map[key].kor;
        return string.Empty;
    }
}

 위의 클래스는 게임 내 사용할 텍스트를 관리하는 클래스로, 싱글톤이다. 앞서 구현한 제네릭 클래스를 이용해 만들었다.

아래는 싱글톤 클래스를 사용한 예 이다.

JArray token_common = (JArray)json_object["common"];
foreach (JObject item in token_common)
{
    jdText text = JsonConvert.DeserializeObject<jdText>(item.ToString());
    TextManager.Instance.AddText(text);
}

 

profile

겨울팥죽 여름빙수

@여름빙수

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!