|
| 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 | +# Incorrecto |
| 19 | + |
| 20 | + |
| 21 | +class GeometricForm: |
| 22 | + def draw_square(self): |
| 23 | + print("Drawing a square") |
| 24 | + |
| 25 | + def draw_circle(self): |
| 26 | + print("Drawing a circle") |
| 27 | + |
| 28 | + |
| 29 | +# Correcto |
| 30 | + |
| 31 | + |
| 32 | +class GeometricForm: |
| 33 | + def draw(self): |
| 34 | + pass |
| 35 | + |
| 36 | + |
| 37 | +class Square(GeometricForm): |
| 38 | + def draw(self): |
| 39 | + print("Drawing a square!") |
| 40 | + |
| 41 | + |
| 42 | +class Circle(GeometricForm): |
| 43 | + def draw(self): |
| 44 | + print("Drawing a circle!") |
| 45 | + |
| 46 | + |
| 47 | +""" |
| 48 | + * DIFICULTAD EXTRA (opcional): |
| 49 | + * Desarrolla una calculadora que necesita realizar diversas operaciones matemáticas. |
| 50 | + * Requisitos: |
| 51 | + * - Debes diseñar un sistema que permita agregar nuevas operaciones utilizando el OCP. |
| 52 | + * Instrucciones: |
| 53 | + * 1. Implementa las operaciones de suma, resta, multiplicación y división. |
| 54 | + * 2. Comprueba que el sistema funciona. |
| 55 | + * 3. Agrega una quinta operación para calcular potencias. |
| 56 | + * 4. Comprueba que se cumple el OCP. |
| 57 | +""" |
| 58 | + |
| 59 | + |
| 60 | +# Import Abstract Base Class and abstractmethod decorator |
| 61 | +from abc import ABC, abstractmethod |
| 62 | + |
| 63 | + |
| 64 | +# Create the abstract class -> avoid's creating instances of this class, but |
| 65 | +# still allows to inherit from it |
| 66 | +class Operation(ABC): |
| 67 | + @abstractmethod |
| 68 | + def calculate(self, num_one, num_two): |
| 69 | + pass |
| 70 | + |
| 71 | + |
| 72 | +# Create the different operations |
| 73 | + |
| 74 | + |
| 75 | +class Sum(Operation): |
| 76 | + def calculate(self, num_one, num_two): |
| 77 | + return num_one + num_two |
| 78 | + |
| 79 | + |
| 80 | +class Subtraction(Operation): |
| 81 | + def calculate(self, num_one, num_two): |
| 82 | + return num_one - num_two |
| 83 | + |
| 84 | + |
| 85 | +class Multiplication(Operation): |
| 86 | + def calculate(self, num_one, num_two): |
| 87 | + return num_one * num_two |
| 88 | + |
| 89 | + |
| 90 | +class Division(Operation): |
| 91 | + def calculate(self, num_one, num_two): |
| 92 | + return num_one / num_two |
| 93 | + |
| 94 | + |
| 95 | +# Create the Calculator class |
| 96 | +class Calculator: |
| 97 | + def __init__(self) -> None: |
| 98 | + self.operations = dict() |
| 99 | + |
| 100 | + def set_operation(self, name: str, operation: object): |
| 101 | + """Allow adding new operations to the current calculator instance.""" |
| 102 | + |
| 103 | + if not isinstance(name, str): |
| 104 | + raise ValueError("The operation name must be an string!") |
| 105 | + self.operations[name] = operation |
| 106 | + |
| 107 | + def calculate(self, name: str, num_one, num_two): |
| 108 | + """Checks if the given operation name exists and returns the value of |
| 109 | + the operation.""" |
| 110 | + |
| 111 | + if name not in self.operations: |
| 112 | + raise ValueError(f"The operation '{name}' doesn't exist!") |
| 113 | + return self.operations[name].calculate(num_one, num_two) |
| 114 | + |
| 115 | + |
| 116 | +# Create the Calculator's instance and set different operations |
| 117 | +calculator = Calculator() |
| 118 | +calculator.set_operation("sum", Sum()) |
| 119 | +calculator.set_operation("subtract", Subtraction()) |
| 120 | +calculator.set_operation("multiply", Multiplication()) |
| 121 | +calculator.set_operation("divide", Division()) |
| 122 | + |
| 123 | +# Check if operations work |
| 124 | +print(calculator.calculate("sum", 10, 2)) # 12 |
| 125 | +print(calculator.calculate("subtract", 10, 2)) # 8 |
| 126 | +print(calculator.calculate("multiply", 10, 2)) # 20 |
| 127 | +print(calculator.calculate("divide", 10, 2)) # 5.0 |
| 128 | +# print(calculator.calculate("pow", 10, 2)) # The operation 'pow' doesn't exist |
| 129 | + |
| 130 | + |
| 131 | +# Create the new Pow operation |
| 132 | +class Pow(Operation): |
| 133 | + def calculate(self, num_one, num_two): |
| 134 | + return num_one**num_two |
| 135 | + |
| 136 | + |
| 137 | +# Set it to the calculator |
| 138 | +calculator.set_operation("pow", Pow()) |
| 139 | + |
| 140 | +# Check if operation works |
| 141 | +print(calculator.calculate("pow", 10, 2)) # 100 |
0 commit comments