Created
August 1, 2019 15:25
-
-
Save eltray/d8020309289904bd427acff881e6855a to your computer and use it in GitHub Desktop.
Learning Dart - 4 Create a factory via top-level function
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' 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