diff --git a/lib/main.dart b/lib/main.dart index 98245b5..e24e310 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -20,6 +20,32 @@ class MyApp extends StatelessWidget { } } +abstract class ShapeFactory { + Widget build(Size size, Color color); +} + +class SquareFactory extends ShapeFactory { + @override + Widget build(Size size, Color color) { + return SizedBox.fromSize( + size: size, + child: Container(color: color), + ); + } +} + +class CircleFactory extends ShapeFactory { + @override + Widget build(Size size, Color color) { + return SizedBox.fromSize( + size: size, + child: Container( + decoration: BoxDecoration(shape: BoxShape.circle, color: color), + ), + ); + } +} + class MyHomePage extends StatefulWidget { const MyHomePage({super.key}); @@ -28,6 +54,18 @@ class MyHomePage extends StatefulWidget { } class _MyHomePageState extends State { + final List shapeFactories = [CircleFactory(), SquareFactory()]; + int factoryIndex = 0; + ShapeFactory get factory => shapeFactories[factoryIndex]; + + void swapFactories() { + if (factoryIndex == 0) { + setState(() => factoryIndex = 1); + return; + } + setState(() => factoryIndex = 0); + } + @override Widget build(BuildContext context) { return Scaffold( @@ -39,12 +77,17 @@ class _MyHomePageState extends State { child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - const Text( - 'You have pushed the button this many times:', - ), - Text( - 'some text', - style: Theme.of(context).textTheme.headlineMedium, + const Text('Abstract Factories!!'), + Text('Using ${shapeFactories[factoryIndex].runtimeType.toString()}'), + ...List.generate( + 3, + (index) => factory.build( + Size(20.0 * (index + 1), 30.0 * (index + 1)), + [Colors.red, Colors.green, Colors.blue][index], + )), + ElevatedButton( + onPressed: () => swapFactories(), + child: const Text('Swap Factories'), ), ], ),