|
| 1 | +#23 { Retos para Programadores } PATRONES DE DISEÑO: SINGLETON |
| 2 | + |
| 3 | +# Bibliography reference |
| 4 | +# I use GPT as a reference and sometimes to correct or generate proper comments. |
| 5 | + |
| 6 | +""" |
| 7 | + * EJERCICIO: |
| 8 | + * Explora el patrón de diseño "singleton" y muestra cómo crearlo |
| 9 | + * con un ejemplo genérico. |
| 10 | + * |
| 11 | + * DIFICULTAD EXTRA (opcional): |
| 12 | + * Utiliza el patrón de diseño "singleton" para representar una clase que |
| 13 | + * haga referencia a la sesión de usuario de una aplicación ficticia. |
| 14 | + * La sesión debe permitir asignar un usuario (id, username, nombre y email), |
| 15 | + * recuperar los datos del usuario y borrar los datos de la sesión. |
| 16 | +
|
| 17 | +""" |
| 18 | + |
| 19 | +log = print |
| 20 | +log('Retos para Programadores #23') |
| 21 | + |
| 22 | +# The Singleton design pattern ensures that a class has a single instance |
| 23 | +# and provides a global point of access to that instance. Below, I will show |
| 24 | +# you how to implement the Singleton pattern in Python, followed by an example |
| 25 | +# that represents a class for managing user sessions. |
| 26 | + |
| 27 | +# Implementation of the Singleton Pattern |
| 28 | + |
| 29 | +class Singleton: |
| 30 | + _instance = None # Class variable to hold the single instance |
| 31 | + |
| 32 | + def __new__(cls): |
| 33 | + if cls._instance is None: |
| 34 | + cls._instance = super(Singleton, cls).__new__(cls) |
| 35 | + # Initialize any properties you need here |
| 36 | + return cls._instance |
| 37 | + |
| 38 | + # Example method |
| 39 | + def some_method(self): |
| 40 | + print("This is a method of the singleton.") |
| 41 | + |
| 42 | +# Using the Singleton |
| 43 | +instance1 = Singleton() |
| 44 | +instance2 = Singleton() |
| 45 | + |
| 46 | +# Note: both variables point to the same instance |
| 47 | +log(instance1.some_method()) # This is a method of the singleton. |
| 48 | +log(instance1 is instance2) # True |
| 49 | + |
| 50 | +# EXTRA DIFFICULTY EXERCISE |
| 51 | + |
| 52 | +class UserSession: |
| 53 | + _instance = None # Class variable to hold the single instance |
| 54 | + |
| 55 | + def __new__(cls): |
| 56 | + if cls._instance is None: |
| 57 | + cls._instance = super(UserSession, cls).__new__(cls) |
| 58 | + cls._instance.user = None # Initialize user property |
| 59 | + return cls._instance |
| 60 | + |
| 61 | + def set_user(self, id, username, name, email): |
| 62 | + self.user = {'id': id, 'username': username, 'name': name, 'email': email} |
| 63 | + |
| 64 | + def get_user(self): |
| 65 | + return self.user |
| 66 | + |
| 67 | + def clear_session(self): |
| 68 | + self.user = None |
| 69 | + |
| 70 | +# Example usage of UserSession |
| 71 | +session1 = UserSession() |
| 72 | +session1. set_user( 1, 'FritzCat', 'Fritz Cat', '[email protected]') |
| 73 | + |
| 74 | +log( session1. get_user()) # {'id': 1, 'username': 'FritzCat', 'name': 'Fritz Cat', 'email': '[email protected]'} |
| 75 | + |
| 76 | +session2 = UserSession() |
| 77 | +log( session2. get_user()) # {'id': 1, 'username': 'FritzCat', 'name': 'Fritz Cat', 'email': '[email protected]'} |
| 78 | + |
| 79 | +session2.clear_session() |
| 80 | +log(session1.get_user()) |
| 81 | + |
| 82 | + # Note: |
| 83 | +""" |
| 84 | +When you call session2.clear_session(), it sets the user attribute to None. Since both session1 and session2 refer to the same instance, calling session1.get_user() afterward will also return None. |
| 85 | +
|
| 86 | +""" |
| 87 | + |
0 commit comments