Last active
May 15, 2018 03:14
-
-
Save naushad-madakiya/dfe7294a1b6ad3928fc8356c2875f96e to your computer and use it in GitHub Desktop.
Intro to Dart for Java Developers: Create a factory
This file contains 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 new Circle(2); | |
if (type == 'square') return new Square(2); | |
throw "Can\'t create of type '$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() { | |
try { | |
print(new Shape('circle').area); | |
print(new Shape('square').area); | |
print(new Shape('wrong').area); // throw and exception | |
} catch (error) { | |
print(error); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment