I'm following a book that uses a factory method to implement a class that is a singleton.
I understand that the main purpose of this is to have just one instance of the class; But what exactly the keyword "factory" does in flutter?
This is the piece of code that I'm referring:
static final DbHelper _dbHelper = DbHelper._internal();
DbHelper._internal();
factory DbHelper() => _dbHelper;
I supose that the _dbHelper
is the single instance that is being create with the _internal
named constructor
and that the factory method returns this single instance, is that correct? Am I missing something?
Factory Method is referred as a creational design pattern which provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. Also known as virtual constructors. Lets clear it with a small code.
Factory Method Pattern allows the sub-classes to choose the type of objects to create. It promotes the loose-coupling by eliminating the need to bind application-specific classes into the code.
The factory design pattern is used when we have a superclass with multiple sub-classes and based on input, we need to return one of the sub-class. This pattern takes out the responsibility of the instantiation of a class from the client program to the factory class.
The factory method is a smart way to create objects in Java and provides several advantages over the traditional approach of creating objects using constructors in Java. It can also improve the quality of code by making the code more readable, less coupled, and improves performance by caching.
You have it correct!
You can read more about factory constructors here: https://dart.dev/guides/language/language-tour#factory-constructors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With