1
+ # ---------------------------------------------
2
+ # Ejemplo de Principio de responsabilidad única
3
+ # ---------------------------------------------
4
+
5
+ # El siguiente ejemplo muestra un código que viola el principio de responsabilidad única.
6
+ # La clase ImageManager tiene dos responsabilidades:
7
+ # 1.- Obtener estadísticas de una imagen
8
+ # 2.- Graficar una imagen
9
+
10
+ import matplotlib .pyplot as plt
11
+ import numpy as np
12
+
13
+ import logging
14
+
15
+
16
+ class ImageManager :
17
+ def __init__ (self , array ):
18
+ self .array = array
19
+
20
+ def get_statistics (self ):
21
+ return {
22
+ "mean" : np .mean (self .array ),
23
+ "std" : np .std (self .array ),
24
+ }
25
+
26
+ def plot (self ):
27
+ fig , ax = plt .subplots ()
28
+ ax .plot (self .array )
29
+ plt .show ()
30
+
31
+ # Para cumplir con el principio de responsabilidad única, separamos las responsabilidades en dos clases diferentes.
32
+
33
+ class ImageStatistics :
34
+ def __init__ (self , array ):
35
+ self .array = array
36
+
37
+ def get_statistics (self ):
38
+ return {
39
+ "mean" : np .mean (self .array ),
40
+ "std" : np .std (self .array ),
41
+ }
42
+
43
+ class ImagePlotter :
44
+ def __init__ (self , array ):
45
+ self .array = array
46
+
47
+ def plot (self ):
48
+ fig , ax = plt .subplots ()
49
+ ax .plot (self .array )
50
+ plt .show ()
51
+
52
+
53
+ # ---------------------------------------------
54
+ # Dificultad extra
55
+ # Sistema de gestion para una bibioteca
56
+ #
57
+ # FORMA INCORRECTA
58
+ #
59
+ # ---------------------------------------------
60
+
61
+ logging .basicConfig (level = logging .INFO , format = "%(asctime)s - %(message)s" )
62
+
63
+ class Library :
64
+ def __init__ (self ):
65
+ self .books = []
66
+ self .users = []
67
+
68
+ def add_user (self , name : str , id : int , email : str ):
69
+ self .users .append ({
70
+ "name" : name ,
71
+ "id" : id ,
72
+ "email" : email ,
73
+ "books" : [],
74
+ }
75
+ )
76
+ logging .info (f"User { name } added successfully" )
77
+
78
+ def add_book (self , title : str , author : str , copies : int ):
79
+ self .books .append ({
80
+ "title" : title ,
81
+ "author" : author ,
82
+ "copies" : copies
83
+ }
84
+ )
85
+ logging .info (f"Book { title } added successfully" )
86
+
87
+ def print_books (self ):
88
+ for book in self .books :
89
+ print (f"\t Title: { book ['title' ]} , Author: { book ['author' ]} , Copies: { book ['copies' ]} " )
90
+
91
+ def print_users (self ):
92
+ for user in self .users :
93
+ print (f"\t Name: { user ['name' ]} , ID: { user ['id' ]} , Email: { user ['email' ]} , Books: { user ['books' ]} " )
94
+
95
+
96
+ def lend_book (self , title : str , name : str ):
97
+
98
+ for book in self .books :
99
+ if book ["title" ] == title :
100
+ if book ["copies" ] > 0 :
101
+ book ["copies" ] -= 1
102
+ logging .info (f"Book { title } borrowed by user { name } " )
103
+ else :
104
+ logging .info (f"Book { title } is not available" )
105
+ break
106
+ else :
107
+ logging .warning (f"Book { title } not found" )
108
+
109
+ for user in self .users :
110
+ if user ["name" ] == name :
111
+ user ["books" ].append (
112
+ {
113
+ "title" : title ,
114
+ }
115
+ )
116
+ logging .info (f"Book { title } added to user { name } " )
117
+ break
118
+
119
+ def return_book (self , title : str , name : str ):
120
+
121
+ for book in self .books :
122
+ if book ["title" ] == title :
123
+ book ["copies" ] += 1
124
+ logging .info (f"Book { title } returned by user { name } " )
125
+ break
126
+ else :
127
+ logging .warning (f"Book { title } not found" )
128
+
129
+ for user in self .users :
130
+ if user ["name" ] == name :
131
+ for book in user ["books" ]:
132
+ if book ["title" ] == title :
133
+ user ["books" ].remove (book )
134
+ logging .info (f"Book { title } removed from user { name } " )
135
+ break
136
+
137
+
138
+ # Testing the class
139
+ print ("\n " * 3 )
140
+ print ("### Testing: Dificultad extra (FORMA INCORRECTA)\n " )
141
+ my_library = Library ()
142
+ my_library .add_user ("Alice" , 1 , "alice@dev" )
143
+ my_library .add_user ("Bob" , 2 , "bob@dev" )
144
+
145
+ my_library .add_book ("The Hobbit" , "J.R.R. Tolkien" , 5 )
146
+ my_library .add_book ("The Lord of the Rings" , "J.R.R. Tolkien" , 3 )
147
+
148
+ print ("\n Books in the library:" )
149
+ my_library .print_books ()
150
+
151
+ my_library .lend_book ("The Hobbit" , "Alice" )
152
+
153
+ print ("\n Books in the library:" )
154
+ my_library .print_books ()
155
+ my_library .print_users ()
156
+
157
+
158
+ my_library .return_book ("The Hobbit" , "Alice" )
159
+ my_library .print_books ()
160
+ my_library .print_users ()
161
+
162
+
163
+ # ---------------------------------------------
164
+ # Dificultad extra
165
+ # Sistema de gestion para una bibioteca
166
+ #
167
+ # Forma CORRECTA
168
+ #
169
+ # Se crean dos clases diferentes, BooksManager y UsersManager, para manejar los libros y a los usuarios.
170
+ # Se crea una clase que maneja la biblioteca y delega las responsabilidades a las clases BooksManeger y UsersManager.
171
+ # ---------------------------------------------
172
+
173
+ class BooksManeger :
174
+ def __init__ (self ):
175
+ self .books = []
176
+
177
+ def add_book (self , title : str , author : str , copies : int ):
178
+ self .books .append (
179
+ {"title" : title , "author" : author , "copies" : copies }
180
+ )
181
+ logging .info (f"Book { title } added successfully" )
182
+
183
+ def print_books (self ):
184
+ for book in self .books :
185
+ print (f"\t Title: { book ['title' ]} , Author: { book ['author' ]} , Copies: { book ['copies' ]} " )
186
+
187
+ def lend_book (self , title : str ):
188
+ for book in self .books :
189
+ if book ["title" ] == title :
190
+ if book ["copies" ] > 0 :
191
+ book ["copies" ] -= 1
192
+ logging .info (f"Book { title } borrowed" )
193
+ else :
194
+ logging .info (f"Book { title } is not available" )
195
+ break
196
+ else :
197
+ logging .warning (f"Book { title } not found" )
198
+
199
+ def return_book (self , title : str ):
200
+ for book in self .books :
201
+ if book ["title" ] == title :
202
+ book ["copies" ] += 1
203
+ logging .info (f"Book { title } returned" )
204
+ break
205
+ else :
206
+ logging .warning (f"Book { title } not found" )
207
+
208
+
209
+ class UsersManager :
210
+ def __init__ (self ):
211
+ self .users = []
212
+
213
+ def add_user (self , name : str , id : int , email : str ):
214
+ self .users .append (
215
+ {"name" : name , "id" : id , "email" : email , "books" : []}
216
+ )
217
+ logging .info (f"User { name } added successfully" )
218
+
219
+ def print_users (self ):
220
+ for user in self .users :
221
+ print (f"\t Name: { user ['name' ]} , ID: { user ['id' ]} , Email: { user ['email' ]} , Books: { user ['books' ]} " )
222
+
223
+ def lend_book (self , title : str , name : str ):
224
+ for user in self .users :
225
+ if user ["name" ] == name :
226
+ user ["books" ].append ({"title" : title })
227
+ logging .info (f"Book { title } added to user { name } " )
228
+ break
229
+ else :
230
+ logging .warning (f"User { name } not found" )
231
+
232
+ def return_book (self , title : str , name : str ):
233
+ for user in self .users :
234
+ if user ["name" ] == name :
235
+ for book in user ["books" ]:
236
+ if book ["title" ] == title :
237
+ user ["books" ].remove (book )
238
+ logging .info (f"Book { title } removed from user { name } " )
239
+ break
240
+ break
241
+ else :
242
+ logging .warning (f"User { name } not found" )
243
+
244
+ class Library_v2 :
245
+ def __init__ (self ):
246
+ self .books_m = BooksManeger ()
247
+ self .users_m = UsersManager ()
248
+
249
+ def add_user (self , name : str , id : int , email : str ):
250
+ self .users_m .add_user (name , id , email )
251
+
252
+ def add_book (self , title : str , author : str , copies : int ):
253
+ self .books_m .add_book (title , author , copies )
254
+
255
+ def print_books (self ):
256
+ self .books_m .print_books ()
257
+
258
+ def print_users (self ):
259
+ self .users_m .print_users ()
260
+
261
+ def lend_book (self , title : str , name : str ):
262
+ self .books_m .lend_book (title )
263
+ self .users_m .lend_book (title , name )
264
+
265
+ def return_book (self , title : str , name : str ):
266
+ self .books_m .return_book (title )
267
+ self .users_m .return_book (title , name )
268
+
269
+
270
+ # Testing the classes
271
+ print ("\n " * 3 )
272
+ print ("### Testing: Dificultad extra (FORMA CORRECTA)\n " )
273
+
274
+ my_library_v2 = Library_v2 ()
275
+ my_library_v2 .add_user ("Alice" , 1 , "alice@dev" )
276
+ my_library_v2 .add_user ("Bob" , 2 , "bob@dev" )
277
+
278
+ my_library_v2 .add_book ("The Hobbit" , "J.R.R. Tolkien" , 5 )
279
+ my_library_v2 .add_book ("The Lord of the Rings" , "J.R.R. Tolkien" , 3 )
280
+
281
+ print ("\n Books in the library:" )
282
+ my_library_v2 .print_books ()
283
+
284
+ my_library_v2 .lend_book ("The Hobbit" , "Alice" )
285
+
286
+ print ("\n Books in the library:" )
287
+ my_library_v2 .print_books ()
288
+
289
+ print ("\n Users in the library:" )
290
+ my_library_v2 .print_users ()
291
+
292
+ my_library_v2 .return_book ("The Hobbit" , "Alice" )
293
+
294
+ print ("\n Books in the library:" )
295
+ my_library_v2 .print_books ()
296
+
297
+ print ("\n Users in the library:" )
298
+ my_library_v2 .print_users ()
0 commit comments