Factory Constructors
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 14 of 110.
A factory constructor is a special constructor that doesn't always create a new instance. Unlike regular constructors, a factory constructor can return an existing instance, a subtype, or even null (if nullable). You declare it using the factory keyword.
class Logger {
static final Logger _instance = Logger._internal();
// Private named constructor
Logger._internal();
// Factory constructor
factory Logger() {
return _instance;
}
}
Logger log1 = Logger();
Logger log2 = Logger();
print(identical(log1, log2)); // trueIn this example, the factory constructor always returns the same instance. No matter how many times you call Logger(), you get the identical object. This pattern is commonly used for implementing singletons.
Factory constructors differ from regular constructors in a key way: they don't have access to this because they might not create a new instance at all. Instead, they must explicitly return an object:
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._(); }Factory constructors are useful when you need control over instance creation, such as returning cached objects, implementing object pools, or deciding which subtype to instantiate based on input parameters.
Challenge
EasyLet's build a notification system that uses factory constructors to create different types of notifications based on a simple string input.
You'll create two files to organize your code:
notification.dart: Define aNotificationclass that serves as the base for all notification types. Your class should have:- A
String messagefield - A private named constructor
Notification._internalthat initializes the message - A factory constructor
Notification(String type, String message)that returns different notification subtypes based on thetypeparameter:- If type is
'email', return anEmailNotification - If type is
'sms', return anSMSNotification - Otherwise, return a
PushNotification
- If type is
- A
send()method that printsSending: [message]
- A
In the same file, create three subclasses that extend Notification:
EmailNotification: Overridesend()to printEmail: [message]SMSNotification: Overridesend()to printSMS: [message]PushNotification: Overridesend()to printPush: [message]
Each subclass needs a constructor that takes a message and passes it to the parent using super._internal(message).
main.dart: Import your notification class and create three notifications using the factory constructor:- An email notification with message
'Welcome!' - An SMS notification with message
'Your code is 1234' - A push notification with message
'New update available'
send()on each notification in the order listed above.- An email notification with message
Expected output:
Email: Welcome!
SMS: Your code is 1234
Push: New update availableCheat sheet
A factory constructor is a special constructor declared with the factory keyword that doesn't always create a new instance. Unlike regular constructors, it can return an existing instance, a subtype, or null.
Factory constructors don't have access to this and must explicitly return an object.
Singleton pattern example:
class Logger {
static final Logger _instance = Logger._internal();
Logger._internal(); // Private named constructor
factory Logger() {
return _instance; // Always returns same instance
}
}
Logger log1 = Logger();
Logger log2 = Logger();
print(identical(log1, log2)); // trueReturning different subtypes:
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._(); }Factory constructors are useful for controlling instance creation, such as returning cached objects, implementing object pools, or deciding which subtype to instantiate based on input parameters.
Try it yourself
import 'notification.dart';
void main() {
// TODO: Create an email notification with message 'Welcome!'
// TODO: Create an SMS notification with message 'Your code is 1234'
// TODO: Create a push notification with message 'New update available'
// TODO: Call send() on each notification in order
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor