Dart
Constructor - 팩토리 생성자
Michelle Hwang
2021. 3. 27. 18:27
1) 기본 생성자 (Default constructor)
2) 이름 있는 생성자 (Named constructor)
3) 초기화 리스트 (Initializer list)
4) 리다이렉팅 생성자 (Redirecting constructor)
5) 상수 생성자 (Constant constructor)
6) 팩토리 생성자 (Factory constructor)
팩토리 생성자는 팩토리 패턴을 사용하기 편리하다. 팩토리 패턴을 사용하면 해당 클래스의 인스턴스를 매번 생성하지 않아도 된다.
보통 자식 클래스의 인스턴스를 리턴 받는다.
void main() {
Person student = Person('Student');
Person employee = Person('Employee');
print('type = ${student.getType()}');
print('type = ${employee.getType()}');
}
class Person {
Person.init();
factory Person(String type) {
switch (type) {
case 'Student':
return Student();
case 'Employee':
return Employee();
}
}
String getType() {
return 'Person';
}
}
class Employee extends Person{
Employee() : super.init();
@override
String getType() {
return 'Employee';
}
}
class Student extends Person{
Student() : super.init();
@override
String getType() {
return 'Student';
}
}
* 결과
type = Student
type = Employee