본문 바로가기
유니티 공부/Unity

Unity - Constructor Chaining(생성자 체이닝)

by 코딩하는 돼징 2023. 12. 3.
반응형

Constructor Chaining

여러 생성자 중에서 가장 많은 입력을 필요로 하는 생성자를 기준으로 하여, 입력할 값의 수가 적은 다른 생성자들을 이 기준이 되는 생성자를 통해 간접적으로 호출하는 기법이다. 이를 통해 코드의 중복을 최소화하고 재사용성을 높일 수 있다.


1. 클래스 내의 생성자들을 연쇄적으로 호출하는 경우 : this() 키워드 사용

01 생성자 체이닝을 사용하지 않는 경우

두번째 생성자와 세번째 생성자에서 this.name = name 코드가 중복되는 것을 확인할 수 있다.

class Piggy
{
    string name = "";
    int weight = 0:
    
    public Piggy()
    {
    }
    
    public Piggy(string name)
    {
        this.name = name;
    }
    
    public Piggy(string name, int weight)
    {
        this.name = name;
        this.weight = weight;
    }
}

02 생성자 체이닝을 사용하는 경우

두번째 생성자와 세번째 생성자에서 this.name = name 코드가 중복된 것이 없어졌음을 확인할 수 있다.

class Piggy
{
    string name = "";
    int weight = 0;
    
    public Piggy() : this("",0)
    {
    }
    
    pubic Piggy(string name) : this(name,0)
    {
    }
    
    public Piggy(string name, int weight)
    {
        this.name = name;
        this.weight = weight;
    }
}

 

2. 부모 클래스로부터 생성자 호출하는 경우 : base()키워드 사용

base를 통해 특정 생성자를 호출할 수 있다.

class Piggy
{
    string name = "";
    int weight = 0;

    public Piggy() : this("", 0)
    {
    }

    public Piggy(string name) : this(name, 0)
    {
    }

    public Piggy(string name, int weight)
    {
        this.name = name;
        this.weight = weight;
    }
}

class Piggy2 : Piggy
{
    int weight2 = 0;
    string name2 = "";
    
    public Piggy2(string name2,string name) : base(name,0)
    {
         this.name2 = name2;
    }
    
    public Piggy2(int weight2, int weight, string name) : base(name, weight)
    {
        this.weight2 = weight2;
    }
}

 

반응형

댓글