Junior — Middle
What is the role and application of factory method patterns in programming?
sobes.tech AI
Answer from AI
The Factory Method pattern is used to create objects without specifying the exact class of the object that will be created. It defines an interface for creating an object but allows subclasses to decide which class to instantiate.
In Flutter (and in programming in general), factory methods are used for:
- Encapsulating the logic of object creation, especially if the creation is complex or depends on conditions.
- Allowing changes to the specific class of the created object without modifying the code that uses it.
- Simplifying testing and extensibility of the code.
Example in Dart/Flutter:
abstract class Button {
void render();
}
class AndroidButton implements Button {
@override
void render() => print('Render Android button');
}
class IOSButton implements Button {
@override
void render() => print('Render iOS button');
}
class Dialog {
Button createButton(String platform) {
if (platform == 'Android') {
return AndroidButton();
} else if (platform == 'iOS') {
return IOSButton();
} else {
throw Exception('Unknown platform');
}
}
void render() {
Button button = createButton('Android');
button.render();
}
}
Here, the createButton method is a factory method that creates different objects depending on the platform.