Dart
factory
Learn flexible creation with factory constructors.
factory constructor
A factory constructor does not have to produce a new instance every time; it may return an existing instance or a subclass instance. It starts with the factory keyword.
Example: factory User.guest() { return User('Guest'); }. The factory body must contain a return; it cannot assign fields directly like a default constructor. Factories fit caching, singletons and conditional creation. A normal constructor always builds a fresh instance; a factory is flexible.
Singleton and caching
The most common use of a factory constructor is the singleton pattern. A static field inside the class holds the instance; the factory returns the same instance on every call.
Example: class Logger { static final Logger _instance = Logger._(); Logger._(); factory Logger() => _instance; }. Here the private named constructor Logger._() is callable only from inside the class; the _instance static field stores it. A Logger() call returns the same instance every time. This shape fits objects that should be unique, such as a logger, configuration or database connection.
Exercise Write the User.guest factory
Define the User class; add a String name field and a User(this.name) default constructor. Write a factory User.guest() { return User('Guest'); } factory constructor. In main, create an instance with var u = User.guest(); and call print(u.name).
Show example solution
// Define the User class
class User {
String name;
User(this.name);
factory User.guest() {
return User('Guest');
}
}
void main() {
var u = User.guest();
print(u.name);
}
Test yourself
-
Add the factory keyword
class User {
String name;
User(this.name);
____ User.guest() { return User('Guest'); }
}
Show answer
class User {
String name;
User(this.name);
factory User.guest() { return User('Guest'); }
}
-
What must a factory constructor return?
- An instance of the class itself
- Only a subclass instance
- Only null
- Nothing at all
Show answer
An instance of the class itself — A factory must return an instance of the class itself; new or existing makes no difference.
-
Match the factory parts
- factory
- Keyword
- return
- Body requirement
- static
- Field holding the instance
Next lesson: Summary - Classes