factoryConstructor
Factory Constructor:
The factory
constructor is a unique constructor in Dart that allows you to control the object creation process. It is often used when you want to return an instance of a class based on certain conditions, reuse existing objects, or implement object caching.
Key characteristics of factory constructors:
Custom Object Creation Logic: Unlike regular constructors, a factory constructor can contain custom logic to create and return objects. It may not necessarily create a new instance every time it's called.
May Return Existing Instances: A factory constructor can decide to return an existing instance instead of creating a new one. This can be useful for implementing the Singleton pattern or object pooling.
Named Constructors: Factory constructors are often defined as named constructors using the
factory
keyword, allowing you to have multiple named constructors in a class.
Here's an example of a factory constructor that implements a simple Singleton pattern:
In this example:
The
Singleton
class has a private constructor_()
to prevent external instantiation.The
factory
constructorSingleton.getInstance()
checks if an instance already exists. If it does, it returns the existing instance; otherwise, it creates a new one.
Initializer List Constructor:
An initializer list constructor is a type of constructor in Dart that allows you to perform additional initialization of fields before the constructor's body runs. It is useful when you need to set up fields with specific values or perform other calculations before the constructor's logic is executed.
Key characteristics of initializer list constructors:
Initialization Before Constructor Body: The initializer list is executed before the constructor's body, ensuring that field initialization happens early in the object creation process.
Use of Colon (:): To define an initializer list constructor, use a colon (
:
) followed by field assignments and other initializations.
Here's an example of an initializer list constructor:
In this example:
The
Point
class has two final fields,x
andy
, which are set in the initializer list.The
assert
statement is used to check thatx
andy
are non-negative values. If the assertions fail, it will throw an error.
Initializer list constructors are particularly useful for setting up the initial state of objects and validating input values before constructing an object. They ensure that field initialization is done correctly and efficiently.
Last updated