Created with <3 with dartpad.dev.
-
-
Save flutterdevrelgists/78a4edb4a99a268420c474ba96c96feb to your computer and use it in GitHub Desktop.
Java-to-Dart codelab: Factory constructor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:math'; | |
abstract class Shape { | |
factory Shape(String type) { | |
if (type == 'circle') return Circle(2); | |
if (type == 'square') return Square(2); | |
throw 'Can\'t create $type.'; | |
} | |
num get area; | |
} | |
class Circle implements Shape { | |
final num radius; | |
Circle(this.radius); | |
@override | |
num get area => pi * pow(radius, 2); | |
} | |
class Square implements Shape { | |
final num side; | |
Square(this.side); | |
@override | |
num get area => pow(side, 2); | |
} | |
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