1
+ // Archivo: eulogioep.java
2
+
3
+ /**
4
+ * PRINCIPIO DE RESPONSABILIDAD ÚNICA (SRP)
5
+ *
6
+ * El Principio de Responsabilidad Única establece que:
7
+ * "Una clase debe tener una única razón para cambiar"
8
+ *
9
+ * Este principio nos ayuda a:
10
+ * - Crear código más mantenible
11
+ * - Facilitar las pruebas unitarias
12
+ * - Reducir el acoplamiento
13
+ * - Mejorar la cohesión del código
14
+ * - Facilitar la reutilización
15
+ */
16
+
17
+ import java .util .ArrayList ;
18
+ import java .util .Date ;
19
+ import java .util .List ;
20
+ import java .util .UUID ;
21
+ import java .util .stream .Collectors ;
22
+
23
+ public class eulogioep {
24
+ public static void main (String [] args ) {
25
+ // Ejemplo de uso del sistema
26
+ try {
27
+ // Creación de los managers
28
+ BookManager bookManager = new BookManager ();
29
+ UserManager userManager = new UserManager ();
30
+ LoanManager loanManager = new LoanManager (bookManager , userManager );
31
+
32
+ // Agregar un libro
33
+ Book book = bookManager .addBook ("El Quijote" , "Miguel de Cervantes" , 5 );
34
+ System .out .println ("Libro agregado: " + book );
35
+
36
+ // Registrar un usuario
37
+ User user =
userManager .
registerUser (
"Juan Pérez" ,
"USER001" ,
"[email protected] " );
38
+ System .out .println ("Usuario registrado: " + user );
39
+
40
+ // Realizar un préstamo
41
+ Loan loan = loanManager .loanBook (user .getId (), book .getId ());
42
+ System .out .println ("Préstamo realizado: " + loan );
43
+
44
+ // Devolver el libro
45
+ loanManager .returnBook (user .getId (), book .getId ());
46
+ System .out .println ("Libro devuelto exitosamente" );
47
+
48
+ // Verificar el estado del libro
49
+ Book updatedBook = bookManager .findBook (book .getId ());
50
+ System .out .println ("Estado actual del libro: " + updatedBook );
51
+
52
+ } catch (Exception e ) {
53
+ System .err .println ("Error: " + e .getMessage ());
54
+ }
55
+ }
56
+ }
57
+
58
+ // ========== IMPLEMENTACIÓN INCORRECTA (Violando SRP) ==========
59
+
60
+ /**
61
+ * Esta implementación viola el SRP porque la clase Library maneja múltiples responsabilidades:
62
+ * 1. Gestión de libros
63
+ * 2. Gestión de usuarios
64
+ * 3. Gestión de préstamos
65
+ */
66
+ class Library {
67
+ private List <Book > books ;
68
+ private List <User > users ;
69
+ private List <Loan > loans ;
70
+
71
+ public Library () {
72
+ this .books = new ArrayList <>();
73
+ this .users = new ArrayList <>();
74
+ this .loans = new ArrayList <>();
75
+ }
76
+
77
+ // Gestión de libros
78
+ public void addBook (String title , String author , int copies ) {
79
+ Book book = new Book (title , author , copies );
80
+ books .add (book );
81
+ }
82
+
83
+ public void removeBook (String bookId ) {
84
+ books .removeIf (book -> book .getId ().equals (bookId ));
85
+ }
86
+
87
+ // Gestión de usuarios
88
+ public void registerUser (String name , String id , String email ) {
89
+ User user = new User (name , id , email );
90
+ users .add (user );
91
+ }
92
+
93
+ public void removeUser (String userId ) {
94
+ users .removeIf (user -> user .getId ().equals (userId ));
95
+ }
96
+
97
+ // Gestión de préstamos
98
+ public void loanBook (String userId , String bookId ) throws Exception {
99
+ Book book = books .stream ()
100
+ .filter (b -> b .getId ().equals (bookId ))
101
+ .findFirst ()
102
+ .orElseThrow (() -> new Exception ("Libro no encontrado" ));
103
+
104
+ User user = users .stream ()
105
+ .filter (u -> u .getId ().equals (userId ))
106
+ .findFirst ()
107
+ .orElseThrow (() -> new Exception ("Usuario no encontrado" ));
108
+
109
+ if (book .getAvailableCopies () <= 0 ) {
110
+ throw new Exception ("No hay copias disponibles" );
111
+ }
112
+
113
+ book .decrementCopies ();
114
+ loans .add (new Loan (userId , bookId , new Date ()));
115
+ }
116
+
117
+ public void returnBook (String userId , String bookId ) throws Exception {
118
+ Loan loan = findLoan (userId , bookId );
119
+ if (loan == null ) {
120
+ throw new Exception ("Préstamo no encontrado" );
121
+ }
122
+
123
+ Book book = books .stream ()
124
+ .filter (b -> b .getId ().equals (bookId ))
125
+ .findFirst ()
126
+ .orElse (null );
127
+
128
+ if (book != null ) {
129
+ book .incrementCopies ();
130
+ }
131
+
132
+ loans .removeIf (l -> l .getUserId ().equals (userId ) && l .getBookId ().equals (bookId ));
133
+ }
134
+
135
+ private Loan findLoan (String userId , String bookId ) {
136
+ return loans .stream ()
137
+ .filter (l -> l .getUserId ().equals (userId ) && l .getBookId ().equals (bookId ))
138
+ .findFirst ()
139
+ .orElse (null );
140
+ }
141
+ }
142
+
143
+ // ========== IMPLEMENTACIÓN CORRECTA (Siguiendo SRP) ==========
144
+
145
+ /**
146
+ * BookManager: Responsable únicamente de la gestión de libros
147
+ */
148
+ class BookManager {
149
+ private List <Book > books ;
150
+
151
+ public BookManager () {
152
+ this .books = new ArrayList <>();
153
+ }
154
+
155
+ public Book addBook (String title , String author , int copies ) {
156
+ Book book = new Book (title , author , copies );
157
+ books .add (book );
158
+ return book ;
159
+ }
160
+
161
+ public void removeBook (String bookId ) {
162
+ books .removeIf (book -> book .getId ().equals (bookId ));
163
+ }
164
+
165
+ public Book findBook (String bookId ) {
166
+ return books .stream ()
167
+ .filter (book -> book .getId ().equals (bookId ))
168
+ .findFirst ()
169
+ .orElse (null );
170
+ }
171
+
172
+ public void updateBookCopies (String bookId , int change ) {
173
+ Book book = findBook (bookId );
174
+ if (book != null ) {
175
+ if (change > 0 ) {
176
+ book .incrementCopies ();
177
+ } else {
178
+ book .decrementCopies ();
179
+ }
180
+ }
181
+ }
182
+
183
+ public List <Book > getAllBooks () {
184
+ return new ArrayList <>(books );
185
+ }
186
+ }
187
+
188
+ /**
189
+ * UserManager: Responsable únicamente de la gestión de usuarios
190
+ */
191
+ class UserManager {
192
+ private List <User > users ;
193
+
194
+ public UserManager () {
195
+ this .users = new ArrayList <>();
196
+ }
197
+
198
+ public User registerUser (String name , String id , String email ) {
199
+ User user = new User (name , id , email );
200
+ users .add (user );
201
+ return user ;
202
+ }
203
+
204
+ public void removeUser (String userId ) {
205
+ users .removeIf (user -> user .getId ().equals (userId ));
206
+ }
207
+
208
+ public User findUser (String userId ) {
209
+ return users .stream ()
210
+ .filter (user -> user .getId ().equals (userId ))
211
+ .findFirst ()
212
+ .orElse (null );
213
+ }
214
+
215
+ public List <User > getAllUsers () {
216
+ return new ArrayList <>(users );
217
+ }
218
+ }
219
+
220
+ /**
221
+ * LoanManager: Responsable únicamente de la gestión de préstamos
222
+ */
223
+ class LoanManager {
224
+ private List <Loan > loans ;
225
+ private final BookManager bookManager ;
226
+ private final UserManager userManager ;
227
+
228
+ public LoanManager (BookManager bookManager , UserManager userManager ) {
229
+ this .loans = new ArrayList <>();
230
+ this .bookManager = bookManager ;
231
+ this .userManager = userManager ;
232
+ }
233
+
234
+ public Loan loanBook (String userId , String bookId ) throws Exception {
235
+ Book book = bookManager .findBook (bookId );
236
+ User user = userManager .findUser (userId );
237
+
238
+ if (book == null || user == null ) {
239
+ throw new Exception ("Libro o usuario no encontrado" );
240
+ }
241
+
242
+ if (book .getAvailableCopies () <= 0 ) {
243
+ throw new Exception ("No hay copias disponibles" );
244
+ }
245
+
246
+ bookManager .updateBookCopies (bookId , -1 );
247
+ Loan loan = new Loan (userId , bookId , new Date ());
248
+ loans .add (loan );
249
+ return loan ;
250
+ }
251
+
252
+ public void returnBook (String userId , String bookId ) throws Exception {
253
+ Loan loan = findLoan (userId , bookId );
254
+ if (loan == null ) {
255
+ throw new Exception ("Préstamo no encontrado" );
256
+ }
257
+
258
+ bookManager .updateBookCopies (bookId , 1 );
259
+ loans .removeIf (l -> l .getUserId ().equals (userId ) && l .getBookId ().equals (bookId ));
260
+ }
261
+
262
+ private Loan findLoan (String userId , String bookId ) {
263
+ return loans .stream ()
264
+ .filter (loan -> loan .getUserId ().equals (userId ) && loan .getBookId ().equals (bookId ))
265
+ .findFirst ()
266
+ .orElse (null );
267
+ }
268
+
269
+ public List <Loan > getAllLoans () {
270
+ return new ArrayList <>(loans );
271
+ }
272
+ }
273
+
274
+ // Clases de modelo
275
+ class Book {
276
+ private final String id ;
277
+ private final String title ;
278
+ private final String author ;
279
+ private int availableCopies ;
280
+
281
+ public Book (String title , String author , int availableCopies ) {
282
+ this .id = UUID .randomUUID ().toString ();
283
+ this .title = title ;
284
+ this .author = author ;
285
+ this .availableCopies = availableCopies ;
286
+ }
287
+
288
+ public String getId () {
289
+ return id ;
290
+ }
291
+
292
+ public String getTitle () {
293
+ return title ;
294
+ }
295
+
296
+ public String getAuthor () {
297
+ return author ;
298
+ }
299
+
300
+ public int getAvailableCopies () {
301
+ return availableCopies ;
302
+ }
303
+
304
+ public void incrementCopies () {
305
+ this .availableCopies ++;
306
+ }
307
+
308
+ public void decrementCopies () {
309
+ this .availableCopies --;
310
+ }
311
+
312
+ @ Override
313
+ public String toString () {
314
+ return "Book{" +
315
+ "id='" + id + '\'' +
316
+ ", title='" + title + '\'' +
317
+ ", author='" + author + '\'' +
318
+ ", availableCopies=" + availableCopies +
319
+ '}' ;
320
+ }
321
+ }
322
+
323
+ class User {
324
+ private final String id ;
325
+ private final String name ;
326
+ private final String email ;
327
+
328
+ public User (String name , String id , String email ) {
329
+ this .name = name ;
330
+ this .id = id ;
331
+ this .email = email ;
332
+ }
333
+
334
+ public String getId () {
335
+ return id ;
336
+ }
337
+
338
+ public String getName () {
339
+ return name ;
340
+ }
341
+
342
+ public String getEmail () {
343
+ return email ;
344
+ }
345
+
346
+ @ Override
347
+ public String toString () {
348
+ return "User{" +
349
+ "id='" + id + '\'' +
350
+ ", name='" + name + '\'' +
351
+ ", email='" + email + '\'' +
352
+ '}' ;
353
+ }
354
+ }
355
+
356
+ class Loan {
357
+ private final String userId ;
358
+ private final String bookId ;
359
+ private final Date loanDate ;
360
+
361
+ public Loan (String userId , String bookId , Date loanDate ) {
362
+ this .userId = userId ;
363
+ this .bookId = bookId ;
364
+ this .loanDate = loanDate ;
365
+ }
366
+
367
+ public String getUserId () {
368
+ return userId ;
369
+ }
370
+
371
+ public String getBookId () {
372
+ return bookId ;
373
+ }
374
+
375
+ public Date getLoanDate () {
376
+ return loanDate ;
377
+ }
378
+
379
+ @ Override
380
+ public String toString () {
381
+ return "Loan{" +
382
+ "userId='" + userId + '\'' +
383
+ ", bookId='" + bookId + '\'' +
384
+ ", loanDate=" + loanDate +
385
+ '}' ;
386
+ }
387
+ }
0 commit comments