Skip to content

Instantly share code, notes, and snippets.

@AlexKenbo
Created November 1, 2019 15:37
Show Gist options
  • Save AlexKenbo/a9080a2cd6181970ad9129f77c86963c to your computer and use it in GitHub Desktop.
Save AlexKenbo/a9080a2cd6181970ad9129f77c86963c to your computer and use it in GitHub Desktop.
Класс Shape создает новые объекты своего типа с заданными параметрами
import 'dart:math';
abstract class Shape {
factory Shape(String type) {
if (type == 'circle') return Circle(3);
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 {
Shape circle = Shape('circle');
print(circle.area);
print(circle.runtimeType);
print(Shape('square').area);
print(Shape('square').runtimeType);
print(Shape('triangle').area);
print(Shape('triangle').runtimeType);
} catch (err) {
print(err);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment