Updated 1 May 2023
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.
Partner with us for custom Flutter app development services.
Lets clear it with a small code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
void main() { Student student = Student(15, "Rahul"); print('Name - ${student.name}'); } class Student { int id; String name; static final Map<String, Student> _cache = <String, Student>{}; factory Student(int id, String name) { return _cache.putIfAbsent(name, () => Student._internal(id, name)); } Student._internal(this.id, this.name); } |
In this way, new object will not be initialized for the student with this name. This is according to this example. You can use it according to your use case.
Dart also supports factory constructors, which can return subtypes.
Let see this use case of factory with an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Square extends Shape {} class Circle extends Shape {} class Shape { Shape(); factory Shape.fromTypeName(String typeName) { if (typeName == 'square') return Square(); if (typeName == 'circle') return Circle(); throw "$typeName shape not recognized."; } } void main() { Shape shape = Shape.fromTypeName('square'); print(shape); } |
So as demonstrated in the above example we make of use of factory to return the Subtype class objects.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.