Skip to content

Commit fba71cb

Browse files
authored
Merge pull request mouredev#4694 from bytecodesky/main
#27 - Python
2 parents 795dc3c + f0cec92 commit fba71cb

File tree

1 file changed

+138
-0
lines changed

1 file changed

+138
-0
lines changed
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
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+
8+
#EL PRINCIPIO SOLID OCP (OPEN-CLOSED PRINCIPLE) ESTABLECE QUE UNA CLASE DEBE ESTAR ABIERTA PARA SU EXTENSIÓN, PERO CERRADA PARA SU MODIFICACIÓN. EN OTRAS PALABRAS, DEBE SER POSIBLE AGREGAR NUEVAS FUNCIONALIDADES A UNA CLASE SIN NECESIDAD DE MODIFICAR SU CÓDIGO FUENTE.
9+
10+
# Ejemplo incorrecto
11+
# En este ejemplo es incorrecto porque si se quiere agregar un nuevo animal, se tendría que modificar la clase Granja para agregar un nuevo método sonido() para el nuevo animal. Esto viola el principio OCP, ya que no se puede extender la funcionalidad de la clase Granja sin modificar su código fuente.
12+
class Animal:
13+
def __init__(self, nombre, sonido):
14+
self.nombre = nombre
15+
self.sonido = sonido
16+
17+
class Granja:
18+
def __init__(self):
19+
self.animales = []
20+
21+
def agregar_animal(self, animal):
22+
self.animales.append(animal)
23+
24+
def sonidos(self):
25+
for animal in self.animales:
26+
print(animal.sonido)
27+
28+
granja = Granja()
29+
granja.agregar_animal(Animal("Firulais", "Guau"))
30+
granja.agregar_animal(Animal("Garfield", "Miau"))
31+
granja.agregar_animal(Animal("Manchitas", "Muu"))
32+
granja.sonidos()
33+
34+
35+
# Ejemplo correcto
36+
# En este ejemplo, se utiliza el principio OCP para permitir la extensión de la funcionalidad de la clase Granja sin modificar su código fuente. Se crea una clase base Animal con un método sonido() que es implementado por las subclases Perro, Gato y Vaca. De esta manera, se puede agregar nuevos animales sin modificar la clase Granja.
37+
class Animal:
38+
def __init__(self, nombre):
39+
self.nombre = nombre
40+
41+
def sonido(self):
42+
pass
43+
44+
class Perro(Animal):
45+
def sonido(self):
46+
return "Guau"
47+
48+
class Gato(Animal):
49+
def sonido(self):
50+
return "Miau"
51+
52+
class Vaca(Animal):
53+
def sonido(self):
54+
return "Muu"
55+
56+
class Granja:
57+
def __init__(self):
58+
self.animales = []
59+
60+
def agregar_animal(self, animal):
61+
self.animales.append(animal)
62+
63+
def sonidos(self):
64+
for animal in self.animales:
65+
print(animal.sonido())
66+
67+
granja = Granja()
68+
granja.agregar_animal(Perro("Firulais"))
69+
granja.agregar_animal(Gato("Garfield"))
70+
granja.agregar_animal(Vaca("Manchitas"))
71+
granja.sonidos()
72+
73+
""" * DIFICULTAD EXTRA (opcional):
74+
* Desarrolla una calculadora que necesita realizar diversas operaciones matemáticas.
75+
* Requisitos:
76+
* - Debes diseñar un sistema que permita agregar nuevas operaciones utilizando el OCP.
77+
* Instrucciones:
78+
* 1. Implementa las operaciones de suma, resta, multiplicación y división.
79+
* 2. Comprueba que el sistema funciona.
80+
* 3. Agrega una quinta operación para calcular potencias.
81+
* 4. Comprueba que se cumple el OCP."""
82+
83+
# IMPLEMENTACIÓN DE UNA CALCULADORA QUE CUMPLE CON EL PRINCIPIO OCP
84+
class Calculadora:
85+
def __init__(self):
86+
self.operaciones = []
87+
88+
def agregar_operacion(self, operacion):
89+
self.operaciones.append(operacion)
90+
91+
def calcular(self, operacion, a, b):
92+
for op in self.operaciones:
93+
if op.nombre == operacion:
94+
return op.calcular(a, b)
95+
return None
96+
97+
class Operacion:
98+
def __init__(self, nombre):
99+
self.nombre = nombre
100+
101+
def calcular(self, a, b):
102+
pass
103+
104+
class Suma(Operacion):
105+
def calcular(self, a, b):
106+
return a + b
107+
108+
class Resta(Operacion):
109+
def calcular(self, a, b):
110+
return a - b
111+
112+
class Multiplicacion(Operacion):
113+
def calcular(self, a, b):
114+
return a * b
115+
116+
class Division(Operacion):
117+
def calcular(self, a, b):
118+
return a / b
119+
120+
# COMPROBACIÓN DE FUNCIONAMIENTO CON LAS OPERACIONES BÁSICAS
121+
calc = Calculadora()
122+
calc.agregar_operacion(Suma("Suma"))
123+
calc.agregar_operacion(Resta("Resta"))
124+
calc.agregar_operacion(Multiplicacion("Multiplicación"))
125+
calc.agregar_operacion(Division("División"))
126+
127+
print(calc.calcular("Suma", 5, 3))
128+
print(calc.calcular("Resta", 5, 3))
129+
print(calc.calcular("Multiplicación", 5, 3))
130+
print(calc.calcular("División", 5, 3))
131+
132+
# AGREGAR UNA NUEVA OPERACIÓN (POTENCIA)
133+
class Potencia(Operacion):
134+
def calcular(self, a, b):
135+
return a ** b
136+
137+
calc.agregar_operacion(Potencia("Potencia"))
138+
print(calc.calcular("Potencia", 5, 3))

0 commit comments

Comments
 (0)