import 'package:flutter/material.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: const MyHomePage(), ); } } 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}); @override State createState() => _MyHomePageState(); } 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( appBar: AppBar( backgroundColor: Theme.of(context).colorScheme.inversePrimary, title: const Text('Abstract Factory'), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ 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'), ), ], ), ), ); } }