I've been struggling with this for a long time.
For sure, what I currently know is that you should use a factory or static fromJson when you need only one object and a Constructor named .fromJson when you need to create multiple instances.
So.. when?? when we need a one instance and when we need multiple instances??
I'm creating a model class for API response right now, and I'm deeply troubled about whether to use the factory or not.
CodePudding user response:
Factory constructor allows returning already created instances. It allows us easily make singletons and multitones. From the call side, it looks like the usual constructor, but from inside implementation, it varies. Also, the factory constructor doesn't force you to return only one instance (object) as you stated. You can create as many as you need. It allows returning already created instances. That's the difference with an ordinary constructor that always returns a new instance. So this feature gives us some flexibility and in some cases performance improvements.
An example:
class Logger {
static Logger _instance;
Logger._() {
print('Logger created');
}
factory Logger() {
return _instance ??= Logger._();
}
void log(String msg) => print('${DateTime.now()}: $msg');
}
void main() {
A().initialize();
B().initialize();
}
class A {
Logger _logger;
void initialize() {
_logger = Logger();
_logger.log('A initialized');
}
}
class B {
Logger _logger;
void initialize() {
_logger = Logger();
_logger.log('B initialized');
}
}
If we run this code it will produce output like that:
Logger created
2021-09-27 21:59:23.887: A initialized
2021-09-27 21:59:23.887: B initialized
Where you can see that only one instance of Logger
class has been created. Despite from calling side we've requested to create two instances.
In most cases, if your task it to create a modal class for API response an ordinary constructor with a static fromJson
method is enough.