Created
July 8, 2023 13:58
-
-
Save hawkkiller/0255a9b8ba902f90b629e9402b8ddffb to your computer and use it in GitHub Desktop.
Open-closed principle example
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
| 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