Junior — Middle
Explain the working principle and purpose of the 'Factory' pattern in software development.
sobes.tech AI
Answer from AI
The 'Factory' pattern is designed for creating objects without the need to explicitly specify the class of the object being created. This allows separating the code that creates objects from their usage, making it easier to extend and maintain.
In Flutter (and Dart), the factory pattern is often used for creating widgets or services, where the specific type of object is chosen dynamically.
Example:
abstract class Button {
void render();
}
class AndroidButton implements Button {
@override
void render() => print('Android Button');
}
class IOSButton implements Button {
@override
void render() => print('iOS Button');
}
class ButtonFactory {
static Button createButton(String platform) {
if (platform == 'android') {
return AndroidButton();
} else if (platform == 'ios') {
return IOSButton();
} else {
throw Exception('Unsupported platform');
}
}
}
void main() {
var button = ButtonFactory.createButton('android');
button.render(); // Outputs: Android Button
}
This approach simplifies adding new button types without changing client code.