|
| 1 | +""" |
| 2 | + SOLID: Principio de Responsibilidad Única (SRP) |
| 3 | + Ejercicio |
| 4 | + Explora el "Principio SOLID de Responsabilidad Única (Single Responsibility |
| 5 | + Principle, SRP)" y crea un ejemplo simple donde se muestre su funcionamiento |
| 6 | + de forma correcta e incorrecta. |
| 7 | +""" |
| 8 | +# Uso incorrecto del SRP |
| 9 | +from typing import Any |
| 10 | + |
| 11 | + |
| 12 | +class User: |
| 13 | + def __init__(self, name, email): |
| 14 | + self.name = name |
| 15 | + self.email = email |
| 16 | + |
| 17 | + def save_user(self): |
| 18 | + print(f"El usuario {self.name} ha sido guardado.") |
| 19 | + |
| 20 | + def print_report(self): |
| 21 | + print(f"Imprimiendo reporte para {self.name} con email {self.email}.") |
| 22 | + |
| 23 | + |
| 24 | +user = User( "Aldroide", "[email protected].") |
| 25 | +user.save_user() |
| 26 | +user.print_report() |
| 27 | + |
| 28 | +# Uso correcto del SRP |
| 29 | + |
| 30 | + |
| 31 | +class User1: |
| 32 | + def __init__(self, name, email): |
| 33 | + self.name = name |
| 34 | + self.email = email |
| 35 | + |
| 36 | + def save(self): |
| 37 | + print(f"Guardando usuario {self.name}.") |
| 38 | + |
| 39 | + |
| 40 | +class Info(): |
| 41 | + def __init__(self, user): |
| 42 | + self.user = user |
| 43 | + |
| 44 | + def print_inform(self): |
| 45 | + print( |
| 46 | + f"Imprimiendo informe para {self.user.name} con email {self.user.email}.") |
| 47 | + |
| 48 | + |
| 49 | +user = User1( "Emmanuel", "[email protected]") |
| 50 | +user.save() |
| 51 | + |
| 52 | +informe = Info(user) |
| 53 | +informe.print_inform() |
| 54 | + |
| 55 | +""" |
| 56 | + DIFICULTAD EXTRA (opcional): |
| 57 | + Desarrolla un sistema de gestión para una biblioteca. El sistema necesita |
| 58 | + manejar diferentes aspectos como el registro de libros, la gestión de usuarios |
| 59 | + y el procesamiento de préstamos de libros. |
| 60 | + Requisitos: |
| 61 | + 1. Registrar libros: El sistema debe permitir agregar nuevos libros con |
| 62 | + información básica como título, autor y número de copias disponibles. |
| 63 | + 2. Registrar usuarios: El sistema debe permitir agregar nuevos usuarios con |
| 64 | + información básica como nombre, número de identificación y correo electrónico. |
| 65 | + 3. Procesar préstamos de libros: El sistema debe permitir a los usuarios |
| 66 | + tomar prestados y devolver libros. |
| 67 | + Instrucciones: |
| 68 | + 1. Diseña una clase que no cumple el SRP: Crea una clase Library que maneje |
| 69 | + los tres aspectos mencionados anteriormente (registro de libros, registro de |
| 70 | + usuarios y procesamiento de préstamos). |
| 71 | + 2. Refactoriza el código: Separa las responsabilidades en diferentes clases |
| 72 | + siguiendo el Principio de Responsabilidad Única. |
| 73 | +""" |
| 74 | + |
| 75 | +# No cumple con el SRP |
| 76 | + |
| 77 | + |
| 78 | +class Library: |
| 79 | + def __init__(self): |
| 80 | + self.books = [] |
| 81 | + self.users = [] |
| 82 | + self.loans = [] |
| 83 | + |
| 84 | + def Register_book(self, title, author, copies): |
| 85 | + book = {'title': title, "author": author, "copies": copies} |
| 86 | + self.books.append(book) |
| 87 | + print(f"Titulo registrado: {title}.") |
| 88 | + |
| 89 | + def Register_user(self, id, name, email): |
| 90 | + user = {'id': id, "name": name, "email": email} |
| 91 | + self.users.append(user) |
| 92 | + print(f"Usuario registrado: {name}.") |
| 93 | + |
| 94 | + def Process_Loans(self, id, title): |
| 95 | + for book in self.books: |
| 96 | + if book["title"] == title and book['copies'] > 0: |
| 97 | + book['copies'] -= 1 |
| 98 | + self.loans.append({'id': id, 'title': title}) |
| 99 | + print(f"Libro prestado: {book['title']} a {id}.") |
| 100 | + return |
| 101 | + print(f"No existen copias disponibles de {title}.") |
| 102 | + |
| 103 | + def Return_book(self, id, title): |
| 104 | + for loan in self.loans: |
| 105 | + if loan["id"] == id and loan["title"] == title: |
| 106 | + self.loans.remove(loan) |
| 107 | + for book in self.books: |
| 108 | + if book["title"] == title: |
| 109 | + book["copies"] += 1 |
| 110 | + print(f"Libro devuelto: {title} por {id}.") |
| 111 | + return |
| 112 | + print(f"No se encontró el prestamo del {title} para {id}. ") |
| 113 | + |
| 114 | + |
| 115 | +library = Library() |
| 116 | +library.Register_book("Baluarte", "Elvira Sastre", 5) |
| 117 | +library.Register_book("Dias sin ti", "Elvira Sastre", 3) |
| 118 | +library.Register_book( |
| 119 | + "Cuarenta y tres maneras de soltarse el pelo", "Elvira Sastre", 5) |
| 120 | +library. Register_user( "Aldo", 1, "[email protected]") |
| 121 | +library. Register_user( "Emmanuel", 2, "[email protected]") |
| 122 | +library. Register_user( "Samira", 3, "[email protected]") |
| 123 | +library.Process_Loans(2, "Baluarte") |
| 124 | +library.Process_Loans(3, "Baluarte") |
| 125 | +library.Return_book(2, "Baluarte") |
| 126 | + |
| 127 | + |
| 128 | +# Codigo Refactorizado cumple con el SRP |
| 129 | +class Book_Manager: |
| 130 | + def __init__(self): |
| 131 | + self.books = [] |
| 132 | + |
| 133 | + def Register_book(self, title, author, copies): |
| 134 | + book = {'title': title, 'author': author, 'copies': copies} |
| 135 | + self.books.append(book) |
| 136 | + print(f"Libro Registrado: {title}.") |
| 137 | + |
| 138 | + def Search_book(self, title): |
| 139 | + for book in self.books: |
| 140 | + if book['title'] == title: |
| 141 | + return book |
| 142 | + return None |
| 143 | + |
| 144 | + |
| 145 | +class User_Manager: |
| 146 | + def __init__(self): |
| 147 | + self.users = [] |
| 148 | + |
| 149 | + def Register_user(self, id, name, email): |
| 150 | + user = {'id': id, "name": name, "email": email} |
| 151 | + self.users.append(user) |
| 152 | + print(f"Usuario registrado: {name}.") |
| 153 | + |
| 154 | + def Search_user(self, id): |
| 155 | + for user in self.users: |
| 156 | + if user['id'] == id: |
| 157 | + return user |
| 158 | + return None |
| 159 | + |
| 160 | + |
| 161 | +class Loan_manager: |
| 162 | + def __init__(self, book_manager, user_manager): |
| 163 | + self.loans = [] |
| 164 | + self.book_manager = book_manager |
| 165 | + self.user_manager = user_manager |
| 166 | + |
| 167 | + def Process_loan(self, id, title): |
| 168 | + user = self.user_manager.Search_user(id) |
| 169 | + book = self.book_manager.Search_book(title) |
| 170 | + |
| 171 | + if user and book and book['copies'] > 0: |
| 172 | + book['copies'] -= 1 |
| 173 | + self.loans.append({'id': id, 'title': title}) |
| 174 | + print(f"Libro prestado {book['title']} a {user['name']}.") |
| 175 | + else: |
| 176 | + print(f"No se puede presta el libro {title}.") |
| 177 | + |
| 178 | + def Return_book(self, id, title): |
| 179 | + for loan in self.loans: |
| 180 | + if loan['id'] == id and loan['title'] == title: |
| 181 | + self.loans.remove(loan) |
| 182 | + book = self.book_manager.Search_book(title) |
| 183 | + if book: |
| 184 | + book['copies'] += 1 |
| 185 | + print(f"Libro devuelto: {title} por {id}.") |
| 186 | + return |
| 187 | + print(f"No se encontro el prestamo de {title} para {id}.") |
| 188 | + |
| 189 | + |
| 190 | +book_manager = Book_Manager() |
| 191 | +user_manager = User_Manager() |
| 192 | +loan_manager = Loan_manager(book_manager, user_manager) |
| 193 | + |
| 194 | +book_manager.Register_book("El Quijote", "Cervantes", 5) |
| 195 | +book_manager.Register_book("La panza del tepozteco", "José Agustin", 3) |
| 196 | + |
| 197 | +user_manager. Register_user( name="Sebastian", id=1, email="[email protected]") |
| 198 | +user_manager. Register_user( name="Erwin", id=2, email="[email protected]") |
| 199 | +loan_manager.Process_loan(1, "El Quijote") |
| 200 | +loan_manager.Return_book(1, "El Quijote") |
0 commit comments