기술(Tech, IT)/알고리즘(Algorithm)

[Algorithm] Nested Constructor (중첩 생성자)

Daniel803 2024. 5. 4. 00:46

Nested Constructor는 일반적으로 클래스의 한 생성자가 같은 클래스의 다른 생성자를 호출해 초기화의 일부를 수행하는 디자인 패턴을 말한다. 이는 공통 초기화 로직을 단일 생성자에서 중앙 집중화하여 코드 중복을 줄이고 유지 관리성을 높이는 데 도움이 될 수 있다. 이 개념은 생성자 오버로딩을 지원하는 Java 및 C++과 같은 언어에서 가장 일반적으로 사용된다. 

 

  • Java
    : Java에서 this() 를 사용해 같은 클래스 내에 다른 생성자를 호출할 수 있다. 'Car(String make, String model)' 생성자는 같은 클래스 내의 다른 생성자를 'this(make, model, 2020)'을 통해 호출할 수 있고 이는 'make'와 'model'을 재사용한다.
public class Car {
    private String make;
    private String model;
    private int year;

    // Constructor with all fields
    public Car(String make, String model, int year) {
        this.make = make;
        this.model = model;
        this.year = year;
    }

    // Constructor that reuses the above constructor
    public Car(String make, String model) {
        this(make, model, 2020); // Default year is 2020
    }
}

 

  • C++
    : 초기화 목록을 사용해 생성자를 호출할 수 있으며, C++ 11에 도임된 생성자 위임 기능을 사용해 한 생성자가 다른 생성자를 호출할 수 있다. 여기서 두 번째 생성자는 기본 연도가 '2020'인 첫 번째 생성자에게 초기화를 위임한다. 중첩 생성자는 초기화 로직을 한 곳에 유지해 수정 및 유지 관리를 간소화하는 데 도움이 된다.
class Car {
private:
    std::string make;
    std::string model;
    int year;

public:
    // Constructor with all fields
    Car(std::string make, std::string model, int year) : make(make), model(model), year(year) {}

    // Constructor that reuses the above constructor
    Car(std::string make, std::string model) : Car(make, model, 2020) {} // Default year is 2020
};