팩토리 생성자
Coddy Dart 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 110개 중 14번째.
factory constructor는 항상 새로운 인스턴스를 생성하지는 않는 특별한 생성자입니다. 일반 생성자와 달리 factory constructor는 기존 인스턴스, 하위 타입 또는 null(널 허용인 경우)을 반환할 수 있습니다. factory 키워드를 사용하여 선언합니다.
class Logger {
static final Logger _instance = Logger._internal();
// 비공개 명명된 생성자
Logger._internal();
// 팩토리 생성자
factory Logger() {
return _instance;
}
}
Logger log1 = Logger();
Logger log2 = Logger();
print(identical(log1, log2)); // true이 예제에서 factory constructor는 항상 동일한 instance를 반환합니다. Logger()를 몇 번 call하더라도 identical 객체를 얻게 됩니다. 이 패턴은 싱글턴을 구현하는 데 흔히 사용됩니다.
Factory 생성자는 일반 생성자와 중요한 차이점이 있습니다. 새로운 instance를 전혀 생성하지 않을 수도 있으므로 this에 액세스할 수 없습니다. 대신 객체를 명시적으로 반환해야 합니다:
class Shape {
factory Shape(String type) {
if (type == 'circle') return Circle();
if (type == 'square') return Square();
return Rectangle();
}
}
class Circle extends Shape { Circle() : super._(); }
class Square extends Shape { Square() : super._(); }
class Rectangle extends Shape { Rectangle() : super._(); }팩토리 생성자는 캐시된 객체를 반환하거나, 객체 풀을 구현하거나, 입력 매개변수를 기반으로 인스턴스화할 하위 타입을 결정하는 등 인스턴스 생성에 대한 제어가 필요할 때 유용합니다.
챌린지
쉬움간단한 문자열 입력을 바탕으로 팩토리 생성자를 사용해 다양한 유형의 알림을 생성하는 알림 시스템을 만들어 보겠습니다.
코드를 정리하기 위해 두 개의 파일을 만듭니다.
notification.dart: 모든 알림 유형의 기반이 되는Notification클래스를 Define합니다. 클래스에는 다음이 있어야 합니다.String messagefield- message를 initializes하는 private named constructor
Notification._internal typeparameter에 따라 서로 다른 알림 하위 유형을 반환하는 factory constructorNotification(String type, String message):- type이
'email'이면EmailNotification반환 - type이
'sms'이면SMSNotification반환 - otherwise
PushNotification반환
- type이
Sending: [message]를 prints하는send()method
같은 파일에서 Notification을 extend하는 세 개의 하위 클래스를 만듭니다.
EmailNotification:Email: [message]를 prints하도록send()를 OverrideSMSNotification:SMS: [message]를 prints하도록send()를 OverridePushNotification:Push: [message]를 prints하도록send()를 Override
각 하위 클래스에는 message를 받는 constructor가 필요하며, super._internal(message)를 사용해 이를 부모 클래스에 전달해야 합니다.
main.dart: notification class를 import하고 factory constructor를 사용해 세 개의 알림을 생성합니다.'Welcome!'message를 사용하는 email notification'Your code is 1234'message를 사용하는 SMS notification'New update available'message를 사용하는 push notification
send()를 Call합니다.
Expected output:
Email: Welcome!
SMS: Your code is 1234
Push: New update available직접 해보기
import 'notification.dart';
void main() {
// TODO: 메시지 'Welcome!'로 이메일 알림을 생성하세요
// TODO: Create an SMS notification with message 'Your code is 1234'
// TODO: Create a push notification with message 'New update available'
// TODO: 각 알림에 순서대로 send()를 호출하세요
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 Dart 컴파일러