Factory Constructors
Factory Constructors
About
- Factories control instance creation.
- Can return existing instances.
- Implement design patterns.
- More flexible than generative constructors.
Main Topics
-
Basic Factory
- **Definition
:
factory` keyword. - Example:
class Logger { factory Logger() => _instance ??= Logger._internal(); }
- **Definition
-
Object Pooling
- **Definition`: Reusing instances.
- Example:
factory Connection.fromPool() {...}
-
Cache Patterns
- **Definition`: Returning cached copies.
- Example:
factory Config.load() => _cache ??= _loadConfig();
-
Subtype Return
- **Definition`: Return different types.
- Example:
factory Shape.fromType(String type) { return type == 'circle' ? Circle() : Square(); }
How to Use
- **Declare
: Use
factory` keyword - **Return`: Existing or new instances
- **Cache`: Implement singleton patterns
- **Flexibility`: Return subtypes
How It Works
- No
this
: Doesn’t create new instance - **No Initializers
: Can't use
this` - **Flexible`: Can return anything
Example Session:
void main() {
var logger = Logger(); // Returns singleton
var shape = Shape.fromType('circle'); // Returns Circle
}
Conclusion
Factory constructors provide controlled object creation points, enabling sophisticated instantiation patterns while maintaining a clean public API surface.