Skip to content

Instantly share code, notes, and snippets.

@kwalrath
Last active November 5, 2022 04:10
Show Gist options
  • Save kwalrath/a6abf3864fcd73a4400b8155f624d899 to your computer and use it in GitHub Desktop.
Save kwalrath/a6abf3864fcd73a4400b8155f624d899 to your computer and use it in GitHub Desktop.
Java-to-Dart codelab: Top-level factory function
import 'dart:math';
abstract class Shape {
num get area;
}
class Circle implements Shape {
final num radius;
Circle(this.radius);
num get area => pi * pow(radius, 2);
}
class Square implements Shape {
final num side;
Square(this.side);
num get area => pow(side, 2);
}
Shape shapeFactory(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
throw 'Can\'t create $type.';
}
main() {
final circle = shapeFactory('circle');
final square = shapeFactory('square');
print(circle.area);
print(square.area);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment