Created
October 31, 2019 16:08
-
-
Save YBCS/154becd924b03c91e29d47d03154d5f3 to your computer and use it in GitHub Desktop.
#4 create a factory of codelabs --> Intro to Dart for Java devs!
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'; | |
// 2 Create a factory constructor | |
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); | |
num get area => pi * pow(radius, 2); | |
} | |
class CircleMock implements Circle { | |
num area; | |
num radius; | |
} | |
class Square implements Shape { | |
final num side; | |
Square(this.side); | |
num get area => pow(side, 2); | |
} | |
// 1 Create a top-level function | |
// 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'); | |
final circle = Shape('circle'); | |
final square = Shape('square'); | |
print(circle.area); | |
print(square.area); | |
} |
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 Circle(2); | |
if (type == 'square') return Square(2); | |
// To trigger exception, don't implement a check for 'triangle'. | |
throw 'Can\'t create $type.'; | |
} | |
num get area; | |
} | |
class Circle implements Shape { | |
final num radius; | |
Circle(this.radius); | |
num get area => pi * pow(radius, 2); | |
} | |
class Square implements Shape { | |
final num side; | |
Square(this.side); | |
num get area => pow(side, 2); | |
} | |
class Triangle implements Shape { | |
final num side; | |
Triangle(this.side); | |
num get area => pow(side, 2) / 2; | |
} | |
main() { | |
try { | |
print(Shape('circle').area); | |
print(Shape('square').area); | |
print(Shape('triangle').area); | |
} catch (err) { | |
print(err); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment