|
| 1 | +/* |
| 2 | +_____________________________________ |
| 3 | +https://github.com/kenysdev |
| 4 | +2024 - JavaScript |
| 5 | +___________________________________________________ |
| 6 | +#26 SOLID: PRINCIPIO DE RESPONSABILIDAD ÚNICA (SRP) |
| 7 | +--------------------------------------------------- |
| 8 | +* EJERCICIO: |
| 9 | + * Explora el "Principio SOLID de Responsabilidad Única (Single Responsibility |
| 10 | + * Principle, SRP)" y crea un ejemplo simple donde se muestre su funcionamiento |
| 11 | + * de forma correcta e incorrecta. |
| 12 | + * |
| 13 | + * DIFICULTAD EXTRA (opcional): |
| 14 | + * Desarrolla un sistema de gestión para una biblioteca. El sistema necesit |
| 15 | + * manejar diferentes aspectos como el registro de libros, la gestión de usuarios |
| 16 | + * y el procesamiento de préstamos de libros. |
| 17 | + * Requisitos: |
| 18 | + * 1. Registrar libros: El sistema debe permitir agregar nuevos libros con |
| 19 | + * información básica como título, autor y número de copias disponibles. |
| 20 | + * 2. Registrar usuarios: El sistema debe permitir agregar nuevos usuarios con |
| 21 | + * información básica como nombre, número de identificación y correo electrónico. |
| 22 | + * 3. Procesar préstamos de libros: El sistema debe permitir a los usuarios |
| 23 | + * tomar prestados y devolver libros. |
| 24 | + * Instrucciones: |
| 25 | + * 1. Diseña una clase que no cumple el SRP: Crea una clase Library que maneje |
| 26 | + * los tres aspectos mencionados anteriormente (registro de libros, registro de |
| 27 | + * usuarios y procesamiento de préstamos). |
| 28 | + * 2. Refactoriza el código: Separa las responsabilidades en diferentes clases |
| 29 | + * siguiendo el Principio de Responsabilidad Única. |
| 30 | +*/ |
| 31 | +// ________________________________________________________ |
| 32 | +// SIN APLICAR SRP |
| 33 | +// --------------- |
| 34 | +class Program { |
| 35 | + constructor() { |
| 36 | + this.customers = []; |
| 37 | + this.suppliers = []; |
| 38 | + } |
| 39 | + |
| 40 | + addCustomer(name) { |
| 41 | + this.customers.push(name); |
| 42 | + } |
| 43 | + |
| 44 | + removeCustomer(name) { |
| 45 | + this.customers = this.customers.filter((customer) => customer !== name); |
| 46 | + } |
| 47 | + |
| 48 | + addSupplier(name) { |
| 49 | + this.suppliers.push(name); |
| 50 | + } |
| 51 | + |
| 52 | + removeSupplier(name) { |
| 53 | + this.suppliers = this.suppliers.filter((supplier) => supplier !== name); |
| 54 | + } |
| 55 | + |
| 56 | + printData() { |
| 57 | + console.log("Clientes:", this.customers); |
| 58 | + console.log("Proveedores:", this.suppliers); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | +// ________________________________________________________ |
| 63 | +// APLICANDO SRP |
| 64 | +// --------------- |
| 65 | + |
| 66 | +class Customers { |
| 67 | + constructor() { |
| 68 | + this.customers = []; |
| 69 | + } |
| 70 | + |
| 71 | + add(name) { |
| 72 | + this.customers.push(name); |
| 73 | + } |
| 74 | + |
| 75 | + remove(name) { |
| 76 | + this.customers = this.customers.filter((customer) => customer !== name); |
| 77 | + } |
| 78 | + |
| 79 | + print() { |
| 80 | + console.log("Clientes:", this.customers); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + class Suppliers { |
| 85 | + constructor() { |
| 86 | + this.suppliers = []; |
| 87 | + } |
| 88 | + |
| 89 | + add(name) { |
| 90 | + this.suppliers.push(name); |
| 91 | + } |
| 92 | + |
| 93 | + remove(name) { |
| 94 | + this.suppliers = this.suppliers.filter((supplier) => supplier !== name); |
| 95 | + } |
| 96 | + |
| 97 | + print() { |
| 98 | + console.log("Proveedores:", this.suppliers); |
| 99 | + } |
| 100 | + } |
| 101 | + |
| 102 | + const customers = new Customers(); |
| 103 | + const suppliers = new Suppliers(); |
| 104 | + |
| 105 | + customers.add("Cliente A"); |
| 106 | + customers.add("Cliente B"); |
| 107 | + suppliers.add("Proveedor X"); |
| 108 | + |
| 109 | + customers.print(); |
| 110 | + suppliers.print(); |
| 111 | + |
| 112 | + customers.remove("Cliente A"); |
| 113 | + suppliers.remove("Proveedor X"); |
| 114 | + |
| 115 | + customers.print(); |
| 116 | + suppliers.print(); |
| 117 | + |
| 118 | + |
| 119 | +// ________________________________________________________ |
| 120 | +// DIFICULTAD EXTRA |
| 121 | +// --------------- |
| 122 | +// SIN APLICAR SRP |
| 123 | +// --------------- |
| 124 | +class Library { |
| 125 | + constructor() { |
| 126 | + this.books = {}; |
| 127 | + this.users = {}; |
| 128 | + this.borrowed = {}; |
| 129 | + } |
| 130 | + |
| 131 | + addBook(id, title, author, stock) { |
| 132 | + if (this.books[id]) { |
| 133 | + this.books[id].stock += stock; |
| 134 | + this.books[id].available += stock; |
| 135 | + console.log("El libro ya existe, se actualizó el inventario."); |
| 136 | + } else { |
| 137 | + this.books[id] = { title, author, stock, available: stock }; |
| 138 | + console.log(`Libro '${title}' agregado.`); |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + addUser(id, name, email) { |
| 143 | + if (this.users[id]) { |
| 144 | + console.log("El usuario ya existe."); |
| 145 | + } else { |
| 146 | + this.users[id] = { name, email }; |
| 147 | + console.log(`Usuario '${name}' agregado.`); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + lendBook(borrowId, userId, bookId) { |
| 152 | + if (!this.books[bookId]) return console.log("El libro no existe."); |
| 153 | + if (!this.users[userId]) return console.log("El usuario no existe."); |
| 154 | + if (this.books[bookId].available <= 0) |
| 155 | + return console.log("El libro no está disponible."); |
| 156 | + |
| 157 | + this.borrowed[borrowId] = { userId, bookId }; |
| 158 | + this.books[bookId].available -= 1; |
| 159 | + console.log(`Libro '${bookId}' prestado.`); |
| 160 | + } |
| 161 | + |
| 162 | + returnBook(borrowId) { |
| 163 | + if (!this.borrowed[borrowId]) return console.log("No existe el préstamo."); |
| 164 | + |
| 165 | + const { bookId } = this.borrowed[borrowId]; |
| 166 | + this.books[bookId].available += 1; |
| 167 | + delete this.borrowed[borrowId]; |
| 168 | + console.log(`Libro '${bookId}' devuelto.`); |
| 169 | + } |
| 170 | +} |
| 171 | + |
| 172 | +// ________________________________________________________ |
| 173 | +// Aplicando SRP: |
| 174 | +// --------------- |
| 175 | + |
| 176 | +// Singleton |
| 177 | +class LibraryData { |
| 178 | + constructor() { |
| 179 | + if (!LibraryData.instance) { |
| 180 | + this.books = {}; |
| 181 | + this.users = {}; |
| 182 | + this.borrowed = {}; |
| 183 | + LibraryData.instance = this; |
| 184 | + } |
| 185 | + return LibraryData.instance; |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +const data = new LibraryData(); |
| 190 | + |
| 191 | +class Books { |
| 192 | + add(id, title, author, stock) { |
| 193 | + if (data.books[id]) { |
| 194 | + data.books[id].stock += stock; |
| 195 | + data.books[id].available += stock; |
| 196 | + console.log("El libro ya existe, se actualizó el inventario."); |
| 197 | + } else { |
| 198 | + data.books[id] = { title, author, stock, available: stock }; |
| 199 | + console.log(`Libro '${title}' agregado.`); |
| 200 | + } |
| 201 | + } |
| 202 | + |
| 203 | + print() { |
| 204 | + console.log("Libros:", data.books); |
| 205 | + } |
| 206 | +} |
| 207 | + |
| 208 | +class Users { |
| 209 | + add(id, name, email) { |
| 210 | + if (data.users[id]) { |
| 211 | + console.log("El usuario ya existe."); |
| 212 | + } else { |
| 213 | + data.users[id] = { name, email }; |
| 214 | + console.log(`Usuario '${name}' agregado.`); |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + print() { |
| 219 | + console.log("Usuarios:", data.users); |
| 220 | + } |
| 221 | +} |
| 222 | + |
| 223 | +class BorrowedBooks { |
| 224 | + lend(borrowId, userId, bookId) { |
| 225 | + if (!data.books[bookId]) return console.log("El libro no existe."); |
| 226 | + if (!data.users[userId]) return console.log("El usuario no existe."); |
| 227 | + if (data.books[bookId].available <= 0) |
| 228 | + return console.log("El libro no está disponible."); |
| 229 | + |
| 230 | + data.borrowed[borrowId] = { userId, bookId }; |
| 231 | + data.books[bookId].available -= 1; |
| 232 | + console.log(`Libro '${bookId}' prestado.`); |
| 233 | + } |
| 234 | + |
| 235 | + returnBook(borrowId) { |
| 236 | + if (!data.borrowed[borrowId]) return console.log("No existe el préstamo."); |
| 237 | + |
| 238 | + const { bookId } = data.borrowed[borrowId]; |
| 239 | + data.books[bookId].available += 1; |
| 240 | + delete data.borrowed[borrowId]; |
| 241 | + console.log(`Libro '${bookId}' devuelto.`); |
| 242 | + } |
| 243 | + |
| 244 | + print() { |
| 245 | + console.log("Préstamos:", data.borrowed); |
| 246 | + } |
| 247 | +} |
| 248 | + |
| 249 | +// --------------- |
| 250 | +const books = new Books(); |
| 251 | +const users = new Users(); |
| 252 | +const borrowed = new BorrowedBooks(); |
| 253 | +console.log("\nDIFICULTAD EXTRA\n") |
| 254 | +books.add(1, "Libro A", "Autor A", 2); |
| 255 | +books.add(2, "Libro B", "Autor B", 3); |
| 256 | + |
| 257 | +users.add(101, "Usuario 1", "[email protected]"); |
| 258 | +users.add(102, "Usuario 2", "[email protected]"); |
| 259 | + |
| 260 | +borrowed.lend(201, 101, 1); |
| 261 | +borrowed.lend(202, 102, 2); |
| 262 | + |
| 263 | +books.print(); |
| 264 | +users.print(); |
| 265 | +borrowed.print(); |
| 266 | + |
| 267 | +borrowed.returnBook(201); |
| 268 | +books.print(); |
| 269 | +borrowed.print(); |
0 commit comments