|
| 1 | + |
| 2 | +""" |
| 3 | +/* |
| 4 | + * EJERCICIO: |
| 5 | + * Explora el patrón de diseño "singleton" y muestra cómo crearlo |
| 6 | + * con un ejemplo genérico. |
| 7 | + * |
| 8 | +""" |
| 9 | + |
| 10 | +class Singleton(): |
| 11 | + |
| 12 | + _instance = None |
| 13 | + |
| 14 | + def __new__(cls): |
| 15 | + if not cls._instance: |
| 16 | + cls._instance = super(Singleton, cls).__new__(cls) |
| 17 | + return cls._instance |
| 18 | + |
| 19 | +class SonSingleton(Singleton): |
| 20 | + pass |
| 21 | + |
| 22 | +my_singleton1 = Singleton() |
| 23 | +my_singleton2 = Singleton() |
| 24 | +my_singleton3 = SonSingleton() |
| 25 | +print(my_singleton1) |
| 26 | +print(my_singleton2) |
| 27 | +print(my_singleton3) |
| 28 | + |
| 29 | +""" |
| 30 | +
|
| 31 | + * DIFICULTAD EXTRA (opcional): |
| 32 | + * Utiliza el patrón de diseño "singleton" para representar una clase que |
| 33 | + * haga referencia a la sesión de usuario de una aplicación ficticia. |
| 34 | + * La sesión debe permitir asignar un usuario (id, username, nombre y email), |
| 35 | + * recuperar los datos del usuario y borrar los datos de la sesión. |
| 36 | + */ |
| 37 | +
|
| 38 | +""" |
| 39 | + |
| 40 | +class UserSession: |
| 41 | + |
| 42 | + id = None |
| 43 | + username = None |
| 44 | + nombre = None |
| 45 | + email = None |
| 46 | + _instance = None |
| 47 | + |
| 48 | + def __new__(cls): |
| 49 | + if not cls._instance: |
| 50 | + cls._instance = super(UserSession, cls).__new__(cls) |
| 51 | + return cls._instance |
| 52 | + |
| 53 | + def new_user(self, id, username, nombre, email): |
| 54 | + self.id = id |
| 55 | + self.username = username |
| 56 | + self.nombre = nombre |
| 57 | + self.email = email |
| 58 | + def show_data_user(self): |
| 59 | + print(f"{self.id , self.username, self.nombre, self.email}") |
| 60 | + |
| 61 | + def clean_data(self): |
| 62 | + self.id = None |
| 63 | + self.username = None |
| 64 | + self.nombre = None |
| 65 | + self.email = None |
| 66 | + |
| 67 | + |
| 68 | + |
| 69 | + |
| 70 | +session1 = UserSession() |
| 71 | +session2 = UserSession() |
| 72 | +print(session1) |
| 73 | +print(session2) |
| 74 | + |
| 75 | +session3 = UserSession() |
| 76 | +session3.new_user(1, "fborjalv", "Borja", "xxxxx@gmail.com") |
| 77 | +session3.show_data_user() |
| 78 | +session3.clean_data() |
| 79 | + |
| 80 | +session4 = UserSession() |
| 81 | +session4.show_data_user() |
| 82 | + |
0 commit comments