shape factory baby
This commit is contained in:
parent
73bf1500f9
commit
398dc157d2
|
@ -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 {
|
class MyHomePage extends StatefulWidget {
|
||||||
const MyHomePage({super.key});
|
const MyHomePage({super.key});
|
||||||
|
|
||||||
|
@ -28,6 +54,18 @@ class MyHomePage extends StatefulWidget {
|
||||||
}
|
}
|
||||||
|
|
||||||
class _MyHomePageState extends State<MyHomePage> {
|
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
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
|
@ -39,12 +77,17 @@ class _MyHomePageState extends State<MyHomePage> {
|
||||||
child: Column(
|
child: Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: <Widget>[
|
children: <Widget>[
|
||||||
const Text(
|
const Text('Abstract Factories!!'),
|
||||||
'You have pushed the button this many times:',
|
Text('Using ${shapeFactories[factoryIndex].runtimeType.toString()}'),
|
||||||
),
|
...List.generate(
|
||||||
Text(
|
3,
|
||||||
'some text',
|
(index) => factory.build(
|
||||||
style: Theme.of(context).textTheme.headlineMedium,
|
Size(20.0 * (index + 1), 30.0 * (index + 1)),
|
||||||
|
[Colors.red, Colors.green, Colors.blue][index],
|
||||||
|
)),
|
||||||
|
ElevatedButton(
|
||||||
|
onPressed: () => swapFactories(),
|
||||||
|
child: const Text('Swap Factories'),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
|
Loading…
Reference in New Issue
Block a user