In Dart, a factory constructor is a special type of constructor that doesn't necessarily create a new instance of its class every time it's called. Instead, it can return an existing instance or even a completely different type of object. This provides flexibility in how objects are created.
Here's a simple example:
// Define a class named Logger
class Logger {
final String name;
static final Map<String, Logger> _cache = {};
// Private constructor
Logger._internal(this.name);
// Factory constructor to manage instances
factory Logger(String name) {
if (_cache.containsKey(name)) {
// If an instance with the same name exists, return it
return _cache[name]!;
} else {
// If not, create a new instance, cache it, and return it
final logger = Logger._internal(name);
_cache[name] = logger;
return logger;
}
}
// Example method
void log(String message) {
print('$name: $message');
}
}
void main() {
// Use the factory constructor to get or create instances of Logger
var logger1 = Logger('Console');
var logger2 = Logger('File');
var logger3 = Logger('Console'); // Reusing the 'Console' instance
// Output messages using the log method
logger1.log('Hello, Logger 1!');
logger2.log('Greetings, Logger 2!');
logger3.log('Another message for Logger 1!');
}
Explanation:
The Logger class has a private constructor _internal and a static _cache map to store instances.
The factory Logger constructor acts as a factory for creating instances of Logger. It checks if an instance with the given name already exists in the cache. If it does, it returns the existing instance; otherwise, it creates a new one, caches it, and returns it.
In the main function, we create three instances of Logger using the factory constructor. The third instance (logger3) reuses the 'Console' instance, demonstrating that the factory constructor can control how instances are created and reused.
In this example, the factory constructor is used to manage and reuse instances, making it a powerful tool for customizing object creation in Dart.