|
| 1 | +/* |
| 2 | +* EJERCICIO: |
| 3 | +* Explora el "Principio SOLID de Responsabilidad Única (Single Responsibility |
| 4 | +* Principle, SRP)" y crea un ejemplo simple donde se muestre su funcionamiento |
| 5 | +* de forma correcta e incorrecta. |
| 6 | +* |
| 7 | +* DIFICULTAD EXTRA (opcional): |
| 8 | +* Desarrolla un sistema de gestión para una biblioteca. El sistema necesita |
| 9 | +* manejar diferentes aspectos como el registro de libros, la gestión de usuarios |
| 10 | +* y el procesamiento de préstamos de libros. |
| 11 | +* Requisitos: |
| 12 | +* 1. Registrar libros: El sistema debe permitir agregar nuevos libros con |
| 13 | +* información básica como título, autor y número de copias disponibles. |
| 14 | +* 2. Registrar usuarios: El sistema debe permitir agregar nuevos usuarios con |
| 15 | +* información básica como nombre, número de identificación y correo electrónico. |
| 16 | +* 3. Procesar préstamos de libros: El sistema debe permitir a los usuarios |
| 17 | +* tomar prestados y devolver libros. |
| 18 | +* Instrucciones: |
| 19 | +* 1. Diseña una clase que no cumple el SRP: Crea una clase Library que maneje |
| 20 | +* los tres aspectos mencionados anteriormente (registro de libros, registro de |
| 21 | +* usuarios y procesamiento de préstamos). |
| 22 | +* 2. Refactoriza el código: Separa las responsabilidades en diferentes clases |
| 23 | +* siguiendo el Principio de Responsabilidad Única. |
| 24 | +*/ |
| 25 | + |
| 26 | +// Ejemplo de Forma incorrecta |
| 27 | + |
| 28 | +class Order { |
| 29 | + constructor(items, taxRate){ |
| 30 | + this.items = items; |
| 31 | + this.taxRate = taxRate; |
| 32 | + } |
| 33 | + |
| 34 | + calculateTotal() { |
| 35 | + let total = this.items.reduce((sum, item) => sum + item[1], 0); |
| 36 | + const discount = 5 |
| 37 | + let tax = (total - discount) * this.taxRate |
| 38 | + return total - discount + tax; |
| 39 | + } |
| 40 | + |
| 41 | + generateInvoice(){ |
| 42 | + const total = this.calculateTotal() |
| 43 | + let invoice = "Factura:\n"; |
| 44 | + this.items.forEach(([item, price]) => { |
| 45 | + invoice += `${item}: $${price}\n`; |
| 46 | + }); |
| 47 | + invoice += `Total (incluyendo impuestos): $${total.toFixed(2)}\n`; |
| 48 | + return invoice; |
| 49 | + } |
| 50 | + |
| 51 | + sendConfirmationEmail(email){ |
| 52 | + const invoice = this.generateInvoice(); |
| 53 | + console.log(`Enviando email a ${email} con la siguiente Factura:\n${invoice}`); |
| 54 | + |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +const order1 = new Order([['item1', 10], ['item2', 20]], 0.1); |
| 59 | +console.log(order1.generateInvoice()); |
| 60 | +order1.sendConfirmationEmail('[email protected]'); |
| 61 | + |
| 62 | + |
| 63 | +// Manera Correcta cumpliendo el Principio de Responsabilidad Única (SRP) |
| 64 | + |
| 65 | +class Order { |
| 66 | + constructor(items){ |
| 67 | + this.items = items; |
| 68 | + } |
| 69 | + |
| 70 | + getTotal() { |
| 71 | + return this.items.reduce((sum, item) => sum + item[1], 0); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +class TaxCalculator { |
| 76 | + constructor(taxRate, discount = 5) { |
| 77 | + this.taxRate = taxRate; |
| 78 | + this.discount = discount; |
| 79 | + } |
| 80 | + |
| 81 | + calculateTax(total) { |
| 82 | + return (total - this.discount) * this.taxRate; |
| 83 | + } |
| 84 | + |
| 85 | + calculateFinalTotal(total) { |
| 86 | + const tax = this.calculateTax(total); |
| 87 | + return total - this.discount + tax; |
| 88 | + } |
| 89 | +} |
| 90 | + |
| 91 | +class InvoiceGenerator { |
| 92 | + generateInvoice(order, finalTotal) { |
| 93 | + let invoice = "Factura:\n"; |
| 94 | + order.items.forEach(([item, price]) => { |
| 95 | + invoice += `${item}: $${price}\n`; |
| 96 | + }); |
| 97 | + invoice += `Total (incluyendo impuestos): $${finalTotal.toFixed(2)}\n`; |
| 98 | + return invoice; |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +class EmailSender { |
| 103 | + sendConfirmationEmail(email, invoice) { |
| 104 | + console.log(`Enviando email a ${email} con la siguiente Factura:\n${invoice}`); |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +// Uso del código |
| 109 | +const order = new Order([['item1', 10], ['item2', 20]]); |
| 110 | +const taxCalculator = new TaxCalculator(0.1); |
| 111 | +const invoiceGenerator = new InvoiceGenerator(); |
| 112 | +const emailSender = new EmailSender(); |
| 113 | + |
| 114 | +const total = order.getTotal(); |
| 115 | +const finalTotal = taxCalculator.calculateFinalTotal(total); |
| 116 | +const invoice = invoiceGenerator.generateInvoice(order, finalTotal); |
| 117 | + |
| 118 | +console.log(invoice); |
| 119 | +emailSender.sendConfirmationEmail('[email protected]', invoice); |
| 120 | + |
| 121 | + |
| 122 | + |
| 123 | +/////////////-------------------------- EXTRA --------------------------- //////////////////////////////// |
| 124 | + |
| 125 | + |
| 126 | +// Manera Incorrecta del ejercicio |
| 127 | + |
| 128 | +class LibraryOne{ |
| 129 | + |
| 130 | + constructor(){ |
| 131 | + this.books = [] |
| 132 | + this.users = [] |
| 133 | + this.loans = [] |
| 134 | + } |
| 135 | + |
| 136 | + addBook(title, author, copies){ |
| 137 | + let book = {"title": title, "author": author, "copies": copies}; |
| 138 | + this.books.push(book) |
| 139 | + } |
| 140 | + |
| 141 | + addUser(name, userId, email){ |
| 142 | + let user = {"name": name, "userId": userId, "email": email}; |
| 143 | + this.users.push(user) |
| 144 | + } |
| 145 | + |
| 146 | + borrowBook(userId, title){ |
| 147 | + for (let book of this.books){ |
| 148 | + if (book.title === title && book.copies > 0){ |
| 149 | + book.copies -= 1; |
| 150 | + const loan = {"userId": userId, "title": title}; |
| 151 | + this.loans.push(loan); |
| 152 | + return `El usuario '${userId}' se presto el libro '${title}'.`; |
| 153 | + } |
| 154 | + } |
| 155 | + return `Libro '${title}' no esta disponible.` |
| 156 | + } |
| 157 | + |
| 158 | + returnBook(userId, title){ |
| 159 | + for (let loan of this.loans){ |
| 160 | + if(loan.userId === userId && loan.title === title){ |
| 161 | + this.loans = this.loans.filter(1 >= 1 !== loan); |
| 162 | + for (let book of this.books){ |
| 163 | + if(book.title === title){ |
| 164 | + book.copies += 1; |
| 165 | + } |
| 166 | + } |
| 167 | + return `Libro '${title}' retornado por el usuario '${userId}'.`; |
| 168 | + } |
| 169 | + } |
| 170 | + return `No hay registro de que el usuario '${userId}' se haya prestado el libro '${title}'.`; |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +const library1 = new LibraryOne(); |
| 175 | + |
| 176 | +library1.addBook("Lord of the Rings", "JRR Tolkien", 4); |
| 177 | +library1.addBook("Harry Potter", "JK Rowling", 2); |
| 178 | + |
| 179 | +library1.addUser("Alice", "1", "[email protected]"); |
| 180 | +library1.addUser("Matias", "2", "[email protected]"); |
| 181 | + |
| 182 | +console.log(library1.borrowBook("1", "Lord of the Rings")); |
| 183 | +console.log(library1.borrowBook("2", "Harry Potter")); |
| 184 | +console.log(library1.borrowBook("1", "Lord of the Rings")); |
| 185 | +console.log(library1.returnBook("2", "The Great Gatsby")); |
| 186 | + |
| 187 | + |
| 188 | +// Manera Correcta cumpliendo el Principio de Responsabilidad Única (SRP) |
| 189 | + |
| 190 | + |
| 191 | +class Library{ |
| 192 | + constructor(){ |
| 193 | + this.books = []; |
| 194 | + this.users = []; |
| 195 | + } |
| 196 | + |
| 197 | + addBook(book){ |
| 198 | + this.books.push(book) |
| 199 | + } |
| 200 | + |
| 201 | + addUser(user){ |
| 202 | + this.users.push(user); |
| 203 | + } |
| 204 | + |
| 205 | + findBook(title){ |
| 206 | + return this.books.find(book => book.title === title) || null; |
| 207 | + } |
| 208 | + |
| 209 | + findUser(userId){ |
| 210 | + return this.users.find(user => user.userId === userId) || null; |
| 211 | + } |
| 212 | + |
| 213 | + totalBooks(){ |
| 214 | + return this.books.reduce((sum, book) => sum + book.copies, 0); |
| 215 | + } |
| 216 | + |
| 217 | + getLibraryInfo(){ |
| 218 | + const totalBooks = this.totalBooks(); |
| 219 | + const booksInfo = this.books.map(book => book.showInfo()); |
| 220 | + return {totalBooks, booksInfo}; |
| 221 | + } |
| 222 | + |
| 223 | +} |
| 224 | + |
| 225 | +class Book{ |
| 226 | + constructor(title, author, copies){ |
| 227 | + this.title = title; |
| 228 | + this.author = author; |
| 229 | + this.copies = copies; |
| 230 | + } |
| 231 | + |
| 232 | + showInfo(){ |
| 233 | + return `'${this.title}' por '${this.author}', numero de copias '${this.copies}'`; |
| 234 | + } |
| 235 | +} |
| 236 | + |
| 237 | +class User{ |
| 238 | + constructor(name, userId, email){ |
| 239 | + this.name = name |
| 240 | + this.userId = userId |
| 241 | + this.email = email |
| 242 | + this.loans = [] |
| 243 | + } |
| 244 | +} |
| 245 | + |
| 246 | +class LoanProcess{ |
| 247 | + borrowBook(library, userId, title){ |
| 248 | + let user = library.findUser(userId); |
| 249 | + let book = library.findBook(title); |
| 250 | + if(book && user){ |
| 251 | + if(book.copies >0){ |
| 252 | + user.loans.push(book) |
| 253 | + book.copies -= 1 |
| 254 | + console.log(`Libro '${book.title}' prestado a '${user.name}'`) |
| 255 | + }else{ |
| 256 | + console.log("Este libro no esta disponible para prestamo") |
| 257 | + } |
| 258 | + }else{ |
| 259 | + console.log("Usuario o libro no encontrado") |
| 260 | + } |
| 261 | + } |
| 262 | + |
| 263 | + returnBook(library, userId, title){ |
| 264 | + let user = library.findUser(userId); |
| 265 | + let book = library.findBook(title); |
| 266 | + if (book && user){ |
| 267 | + const loanIndex = user.loans.indexOf(book); |
| 268 | + if(loanIndex !== -1){ |
| 269 | + user.loans.splice(loanIndex, 1); |
| 270 | + book.copies += 1 |
| 271 | + console.log(`Libro '${book.title}' devuelto por '${user.name}'.`) |
| 272 | + }else{ |
| 273 | + console.log(`No hay registro de que el libro '${book.title}' haya sido prestado a '${user.name}'`) |
| 274 | + } |
| 275 | + }else{ |
| 276 | + console.log("Usuario o libro no encontrado") |
| 277 | + } |
| 278 | + } |
| 279 | +} |
| 280 | + |
| 281 | + |
| 282 | +const library = new Library(); |
| 283 | +const book1 = new Book("Lord of the Rings", "JRR Tolkien", 4); |
| 284 | +const book2 = new Book("1984", "George Orwell", 5); |
| 285 | +const user = new User("Alice", "1", "[email protected]"); |
| 286 | + |
| 287 | +library.addBook(book1); |
| 288 | +library.addBook(book2); |
| 289 | +library.addUser(user); |
| 290 | + |
| 291 | +const loanProcessor = new LoanProcess(); |
| 292 | +loanProcessor.borrowBook(library, "1", "Lord of the Rings"); |
| 293 | +loanProcessor.returnBook(library, "1", "Lord of the Rings"); |
| 294 | + |
| 295 | +// Total de libros en la biblioteca |
| 296 | +const { totalBooks, booksInfo } = library.getLibraryInfo(); |
| 297 | +console.log(`Total de libros en la biblioteca: ${totalBooks}`); |
| 298 | +console.log("Información de la biblioteca:"); |
| 299 | +booksInfo.forEach(info => console.log(info)); |
0 commit comments