1.기본 생성자 사용 (생성자 파라미터 이용)
class Cat {
String name;
int age;
String color;
int thirsty;
Cat(this.name, this.age, this.color, this.thirsty);
}
void main() {
Cat myCat = Cat("Nabi", 2, "White", 10);
print(myCat.name); // Nabi
}
이 방식은 매우 간단하고 다트에서 자주 사용되는 객체 생성 방식
생성자의 매개변수를 바로 클래스 필드에 매핑한다.
2. 초기화 리스트 (Initializer List) 사용
생성자의 필드를 조건이나 표현식을 이용해 초기화하는 방식입니다.
class Dog {
String name;
int age;
String color;
int thirsty;
Dog(String name, int age, String color, int thirsty)
: this.name = name == "홍길동" ? "이름없음" : name,
this.age = age,
this.color = color,
this.thirsty = thirsty;
}
void main() {
Dog myDog = Dog("홍길동", 3, "Brown", 5);
print(myDog.name); // 이름없음
}
이 방법은 클래스 필드를 초기화하기 전에 논리나 조건을 적용할 수 있다.
추가적인 객체 생성 방법
- 명명된 생성자 (Named Constructor) 사용
다트에서는 생성자를 명명하여 여러 생성자를 정의할 수 있습니다. 이 방식은 클래스 내에서 다양한 방식으로 객체를 생성할 수 있게 도와줍니다.
class Cat {
String name;
int age;
String color;
int thirsty;
Cat(this.name, this.age, this.color, this.thirsty);
// Named Constructor
Cat.oldCat(this.name) {
age = 10;
color = "Gray";
thirsty = 5;
}
}
void main() {
Cat oldCat = Cat.oldCat("Nabi");
print(oldCat.age); // 10
}
Cat.oldCat
생성자는 나이 든 고양이를 나타내는 별도의 생성자로, 다른 방식으로 객체를 초기화할 수 있다.- 팩토리 생성자 (Factory Constructor) 사용
factory
키워드를 사용하여 팩토리 생성자를 정의하면, 단순히 새 객체를 반환하는 대신 복잡한 로직을 수행하거나 같은 객체를 여러 번 반환하는 등의 처리가 가능합니다.dart
코드 복사
class Dog {
String name;
int age;
String color;
int thirsty;
Dog(this.name, this.age, this.color, this.thirsty);
// Factory Constructor
factory Dog.createDog(String name) {
if (name == "Buddy") {
return Dog("Buddy", 5, "Black", 10);
} else {
return Dog(name, 1, "White", 5);
}
}
}
void main() {
Dog buddyDog = Dog.createDog("Buddy");
print(buddyDog.age); // 5
}
팩토리 생성자를 사용하면 객체 생성 시 특정 조건을 체크하고, 이미 존재하는 객체를 반환하거나 새로운 객체를 반환하는 등의 로직을 적용할 수 있다.
Share article