Created
December 18, 2021 02:18
-
-
Save xros/17ab0ad00bf32e004e5fa86c51f636eb to your computer and use it in GitHub Desktop.
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'; | |
/* | |
We can use abstract classes to define an interface that can be implemented by subclasses | |
Very powerful: decouples code that uses an interface from its implementation | |
printArea() doesn't need to know that Sqaure and Circle even exist. | |
only needs a Shape argument with an area property | |
*/ | |
abstract class Shape { | |
double get area; | |
const Shape(); | |
factory Shape.fromJson(Map<String, Object> json) { | |
final type = json['type']; | |
switch (type) { | |
case 'square': | |
final side = json['side']; | |
if (side is double) { | |
return Square(side); | |
} | |
throw UnsupportedError('invalid or missing side property'); | |
case 'circle': | |
final radius = json['radius']; | |
if (radius is double) { | |
return Circle(radius); | |
} | |
throw UnsupportedError('invalid or missing radius property'); | |
default: | |
throw UnimplementedError('invalid type $type'); | |
} | |
} | |
} | |
class Square extends Shape { | |
const Square(this.side); | |
final double side; | |
@override | |
double get area => side * side; | |
} | |
class Circle extends Shape { | |
const Circle(this.radius); | |
final double radius; | |
@override | |
double get area => pi * radius * radius; | |
} | |
void printArea(Shape shape) { | |
print(shape.area); | |
} | |
void main() { | |
final shapeJson = [ | |
{ | |
'type': 'square', | |
'side': 10.0, | |
}, | |
{ | |
'type': 'circle', | |
'radius': 5.0, | |
} | |
]; | |
shapeJson.forEach((element) => {printArea(Shape.fromJson(element))}); // same | |
// create a new Mapped List Iterable | |
final shapes = shapeJson.map((e) => Shape.fromJson(e)); // same | |
// get area for each element | |
shapes.forEach(printArea); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output is