shape factory baby

This commit is contained in:
Nathan Anderson 2024-05-02 12:02:08 -06:00
parent 73bf1500f9
commit 398dc157d2

View File

@ -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<MyHomePage> {
final List<ShapeFactory> 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<MyHomePage> {
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
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'),
),
],
),