flutter_design_patterns/lib/main.dart
2024-05-02 15:40:22 -06:00

117 lines
2.8 KiB
Dart

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 ListStrategy<T> {
List<T> compose(List<T> items);
}
class Monkey {
Monkey({required this.name, required this.power});
final String name;
final int power;
@override
String toString() => '$name - Power: $power';
}
class GreatestMonkeyStrategy implements ListStrategy<Monkey> {
@override
List<Monkey> compose(List<Monkey> items) {
return [
items.fold<Monkey>(
Monkey(name: '', power: 0), (aMonkey, bMonkey) => aMonkey.power > bMonkey.power ? aMonkey : bMonkey)
];
}
}
class WeakMonkeysStrategy implements ListStrategy<Monkey> {
@override
List<Monkey> compose(List<Monkey> items) {
return items
.where(
(element) => element.power <= 200,
)
.toList();
}
}
List<Monkey> monkeys = [
Monkey(name: 'Mortimer', power: 25),
Monkey(name: 'ApeMan', power: 354),
Monkey(name: 'Spider', power: 65),
Monkey(name: 'DK', power: 500),
Monkey(name: 'Tim', power: 120),
Monkey(name: 'Kong', power: 25400),
];
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ListStrategy listStrat = WeakMonkeysStrategy();
void swapStrategies() {
if (listStrat.runtimeType == WeakMonkeysStrategy) {
setState(() => listStrat = GreatestMonkeyStrategy());
return;
}
setState(() => listStrat = WeakMonkeysStrategy());
}
@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: <Widget>[
const Text('All monkeys:'),
...monkeys
.map(
(e) => Text(e.toString()),
)
.toList(),
const SizedBox(height: 50),
Text(listStrat.runtimeType.toString()),
...listStrat
.compose(monkeys)
.map(
(e) => Text(e.toString()),
)
.toList(),
const SizedBox(height: 100),
ElevatedButton(onPressed: () => swapStrategies(), child: const Text('Change Strats')),
],
),
),
);
}
}