Skip to content

Instantly share code, notes, and snippets.

@eltray
Created August 1, 2019 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eltray/d8020309289904bd427acff881e6855a to your computer and use it in GitHub Desktop.
Save eltray/d8020309289904bd427acff881e6855a to your computer and use it in GitHub Desktop.
Learning Dart - 4 Create a factory via top-level function
import 'dart:math' as math;
abstract class Shape {
num get area;
}
class Circle implements Shape {
final num radius;
num get area => math.pi * math.pow(radius, 2);
Circle(this.radius);
}
class Square implements Shape {
final num side;
num get area => math.pow(side, 2);
Square(this.side);
}
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