Junior — Middle
Can you give an example of applying the 'Abstract Factory' pattern in development practice?
sobes.tech AI
Answer from AI
The "Abstract Factory" pattern in Flutter is often used to create cross-platform widgets with different styles for Android and iOS. For example, you can define an abstract factory that creates buttons and dialogs, and concrete factories that return Material widgets for Android and Cupertino widgets for iOS.
abstract class UIFactory {
Widget createButton(String text, VoidCallback onPressed);
Widget createDialog(String title, String content);
}
class MaterialFactory implements UIFactory {
@override
Widget createButton(String text, VoidCallback onPressed) {
return ElevatedButton(onPressed: onPressed, child: Text(text));
}
@override
Widget createDialog(String title, String content) {
return AlertDialog(title: Text(title), content: Text(content));
}
}
class CupertinoFactory implements UIFactory {
@override
Widget createButton(String text, VoidCallback onPressed) {
return CupertinoButton(child: Text(text), onPressed: onPressed);
}
@override
Widget createDialog(String title, String content) {
return CupertinoAlertDialog(title: Text(title), content: Text(content));
}
}
// Usage:
UIFactory factory = Platform.isIOS ? CupertinoFactory() : MaterialFactory();
Widget button = factory.createButton('Press me', () { /* action */ });
This approach allows centralized management of styles and components, simplifying support and extension of the application.