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/277fb8fb991469b18517c1fd0a30b50f to your computer and use it in GitHub Desktop.
Save eltray/277fb8fb991469b18517c1fd0a30b50f to your computer and use it in GitHub Desktop.
Learning Dart - 4 Create factory via factory constructor
import 'dart:math' as math;
abstract class Shape {
num get area;
factory Shape(String type) {
if (type == 'circle') return Circle(2);
if (type == 'square') return Square(2);
throw 'Can\'t create $type';
}
}
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);
}
main() {
final circle = Shape('circle');
final square = Shape('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