Skip to content

Instantly share code, notes, and snippets.

@hawkkiller
Created July 8, 2023 13:58
Show Gist options
  • Select an option

  • Save hawkkiller/0255a9b8ba902f90b629e9402b8ddffb to your computer and use it in GitHub Desktop.

Select an option

Save hawkkiller/0255a9b8ba902f90b629e9402b8ddffb to your computer and use it in GitHub Desktop.
Open-closed principle example
sealed class Shape {
double calcSquare();
}
class Circle extends Shape {
Circle(this.radius);
final double radius;
@override
double calcSquare() => 3.14 * radius * radius;
}
class Rectangle extends Shape {
Rectangle(this.width, this.height);
final double width;
final double height;
@override
double calcSquare() => width * height;
}
class SquareCalculator {
double calcSquare(Shape shape) => shape.calcSquare();
}
void main() {
final calculator = SquareCalculator();
final circle = Circle(25);
// prints 1962,5
print(calculator.calcSquare(circle));
final rectangle = Rectangle(10, 20);
/// prints 200
print(calculator.calcSquare(rectangle));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment