1+ /*
2+ * EJERCICIO:
3+ * Explora el "Principio SOLID Abierto-Cerrado (Open-Close Principle, OCP)"
4+ * y crea un ejemplo simple donde se muestre su funcionamiento
5+ * de forma correcta e incorrecta.
6+ *
7+ * DIFICULTAD EXTRA (opcional):
8+ * Desarrolla una calculadora que necesita realizar diversas operaciones matemáticas.
9+ * Requisitos:
10+ * - Debes diseñar un sistema que permita agregar nuevas operaciones utilizando el OCP.
11+ * Instrucciones:
12+ * 1. Implementa las operaciones de suma, resta, multiplicación y división.
13+ * 2. Comprueba que el sistema funciona.
14+ * 3. Agrega una quinta operación para calcular potencias.
15+ * 4. Comprueba que se cumple el OCP.
16+ */
17+
18+ // Violación del OCP
19+ class AreaCalculator {
20+ calculateRectangleArea ( width , height ) {
21+ return width * height ;
22+ }
23+
24+ calculateCircleArea ( radius ) {
25+ return Math . PI ** radius ;
26+ }
27+ }
28+
29+ const calculator = new AreaCalculator ( ) ;
30+ console . log ( calculator . calculateRectangleArea ( 5 , 10 ) ) ;
31+ console . log ( calculator . calculateCircleArea ( 7 ) ) ;
32+
33+ // OCP
34+ class Shape {
35+ area ( ) {
36+ throw new Error ( "Método area debe ser implementado" ) ;
37+ }
38+ }
39+
40+ class Rectangle extends Shape {
41+ constructor ( width , height ) {
42+ super ( ) ;
43+ this . width = width ;
44+ this . height = height ;
45+ }
46+
47+ area ( ) {
48+ return this . width * this . height ;
49+ }
50+ }
51+
52+ class Circle extends Shape {
53+ constructor ( radius ) {
54+ super ( ) ;
55+ this . radius = radius ;
56+ }
57+
58+ area ( ) {
59+ return Math . PI ** this . radius ;
60+ }
61+ }
62+
63+ class AreaCalculatorOCP {
64+ calculateArea ( shape ) {
65+ return shape . area ( ) ;
66+ }
67+ }
68+
69+ const calculatorOCP = new AreaCalculator ( ) ;
70+ const rectangle = new Rectangle ( 10 , 10 ) ;
71+ const circle = new Circle ( 10 ) ;
72+
73+ console . log ( rectangle . area ( ) ) ;
74+ console . log ( circle . area ( ) ) ;
0 commit comments