[C#] Singleton, Prototype Generic

Lingtea_luv·2025년 4월 13일
0

C#

목록 보기
30/37
post-thumbnail

Singleton Generic


public class Singleton<T> where T : Singleton<T>, new()
{
    private static T instance;
    public static T Instance
    {
        get { return instance; }
        set { instance = value; }
    }

    public static T GetInstance()
    {
        if (instance == null)
        {
            instance = new T();
            instance.Init();  
        }
        return instance;
    }

    protected virtual void Init()  
    {

    }
}

Init() : 생성자를 따로 정의할 수 없어, 초기화 함수를 GetInstance에 포함시켜 생성자 역할을 해준다.
instance.Init(); : where T : Singleton<T> 가 있어야한다. => Init()을 사용할 수 있는 조건
instance = new T(); : where T : new() => 인스턴스 생성할 수 있는 조건
where T : Singleton<T>, new() 제네릭부터 써야한다. (서순 중요!)

Prototype


abstract class

public abstract class Prototype<T>
{
    public abstract T Clone();
}

public class Monster : Prototype<Monster>
{
    public string name;
    public Monster(string name)
    {
        this.name = name;
    }
    public override Monster Clone()
    {
        Monster monster = this;
        return monster;
    }
}

interface

public interface IProtoType<T>
{
    public abstract T Clone();
}

public class Monster : IProtoType<Monster>
{
    public string name;
    public Monster(string name)
    {
        this.name = name;
    }
    public Monster Clone()
    {
        Monster monster = this;
        return monster;
    }
}

Main

class Program
{
    static void Main(string[] args)
    {
        Monster monster = new Monster("슬라임");
        Monster monster1 = monster.Clone();

        Console.WriteLine(monster1.name);
    }
}
슬라임
profile
뚠뚠뚠뚠

0개의 댓글