|
| 1 | +public class AnaLauDB { |
| 2 | + |
| 3 | + // ========================================================================== |
| 4 | + // IMPLEMENTACIÓN QUE CUMPLE EL PRINCIPIO DE INVERSIÓN DE DEPENDENCIAS (DIP) |
| 5 | + // ========================================================================== |
| 6 | + |
| 7 | + // 1. ABSTRACCIÓN DE ALTO NIVEL (INTERFAZ) |
| 8 | + // ========================================================================== |
| 9 | + |
| 10 | + // Interfaz que define el contrato para cualquier servicio de notificación |
| 11 | + interface ServicioNotificacion { |
| 12 | + boolean enviarNotificacion(String destinatario, String mensaje); |
| 13 | + |
| 14 | + String getTipoNotificacion(); |
| 15 | + |
| 16 | + boolean validarDestinatario(String destinatario); |
| 17 | + } |
| 18 | + |
| 19 | + // ========================================================================== |
| 20 | + // 2. IMPLEMENTACIONES ESPECÍFICAS (MÓDULOS DE BAJO NIVEL) |
| 21 | + // ========================================================================== |
| 22 | + |
| 23 | + // Implementación específica para Email |
| 24 | + static class ServicioEmail implements ServicioNotificacion { |
| 25 | + private String servidorSMTP; |
| 26 | + |
| 27 | + public ServicioEmail(String servidorSMTP) { |
| 28 | + this.servidorSMTP = servidorSMTP; |
| 29 | + } |
| 30 | + |
| 31 | + @Override |
| 32 | + public boolean enviarNotificacion(String destinatario, String mensaje) { |
| 33 | + if (!validarDestinatario(destinatario)) { |
| 34 | + System.out.println("Error: Email inválido - " + destinatario); |
| 35 | + return false; |
| 36 | + } |
| 37 | + |
| 38 | + System.out.println("ENVIANDO EMAIL..."); |
| 39 | + System.out.println("Servidor SMTP: " + servidorSMTP); |
| 40 | + System.out.println("Para: " + destinatario); |
| 41 | + System.out.println("Mensaje: " + mensaje); |
| 42 | + |
| 43 | + // Simular envío |
| 44 | + try { |
| 45 | + Thread.sleep(1000); |
| 46 | + } catch (InterruptedException e) { |
| 47 | + Thread.currentThread().interrupt(); |
| 48 | + } |
| 49 | + |
| 50 | + System.out.println("Email enviado exitosamente"); |
| 51 | + return true; |
| 52 | + } |
| 53 | + |
| 54 | + @Override |
| 55 | + public String getTipoNotificacion() { |
| 56 | + return "EMAIL"; |
| 57 | + } |
| 58 | + |
| 59 | + @Override |
| 60 | + public boolean validarDestinatario(String destinatario) { |
| 61 | + return destinatario != null && destinatario.contains("@") && destinatario.contains("."); |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // Implementación específica para notificaciones PUSH |
| 66 | + static class ServicioPush implements ServicioNotificacion { |
| 67 | + private String appId; |
| 68 | + |
| 69 | + public ServicioPush(String appId) { |
| 70 | + this.appId = appId; |
| 71 | + } |
| 72 | + |
| 73 | + @Override |
| 74 | + public boolean enviarNotificacion(String destinatario, String mensaje) { |
| 75 | + if (!validarDestinatario(destinatario)) { |
| 76 | + System.out.println("Error: Token de dispositivo inválido"); |
| 77 | + return false; |
| 78 | + } |
| 79 | + |
| 80 | + System.out.println("ENVIANDO NOTIFICACIÓN PUSH..."); |
| 81 | + System.out.println("App ID: " + appId); |
| 82 | + System.out.println("Token del dispositivo: " + destinatario); |
| 83 | + System.out.println("Mensaje: " + mensaje); |
| 84 | + |
| 85 | + // Simular envío |
| 86 | + try { |
| 87 | + Thread.sleep(500); |
| 88 | + } catch (InterruptedException e) { |
| 89 | + Thread.currentThread().interrupt(); |
| 90 | + } |
| 91 | + |
| 92 | + System.out.println("Notificación PUSH enviada exitosamente"); |
| 93 | + return true; |
| 94 | + } |
| 95 | + |
| 96 | + @Override |
| 97 | + public String getTipoNotificacion() { |
| 98 | + return "PUSH"; |
| 99 | + } |
| 100 | + |
| 101 | + @Override |
| 102 | + public boolean validarDestinatario(String destinatario) { |
| 103 | + return destinatario != null && destinatario.length() >= 10; |
| 104 | + } |
| 105 | + } |
| 106 | + |
| 107 | + // Implementación específica para SMS |
| 108 | + static class ServicioSMS implements ServicioNotificacion { |
| 109 | + private String proveedorSMS; |
| 110 | + private String apiKey; |
| 111 | + |
| 112 | + public ServicioSMS(String proveedorSMS, String apiKey) { |
| 113 | + this.proveedorSMS = proveedorSMS; |
| 114 | + this.apiKey = apiKey; |
| 115 | + } |
| 116 | + |
| 117 | + @Override |
| 118 | + public boolean enviarNotificacion(String destinatario, String mensaje) { |
| 119 | + if (!validarDestinatario(destinatario)) { |
| 120 | + System.out.println("Error: Número de teléfono inválido - " + destinatario); |
| 121 | + return false; |
| 122 | + } |
| 123 | + |
| 124 | + System.out.println("ENVIANDO SMS..."); |
| 125 | + System.out.println("Proveedor: " + proveedorSMS); |
| 126 | + System.out.println("A: " + destinatario); |
| 127 | + System.out.println("Mensaje: " + mensaje); |
| 128 | + |
| 129 | + // Simular envío |
| 130 | + try { |
| 131 | + Thread.sleep(800); |
| 132 | + } catch (InterruptedException e) { |
| 133 | + Thread.currentThread().interrupt(); |
| 134 | + } |
| 135 | + |
| 136 | + System.out.println("SMS enviado exitosamente"); |
| 137 | + return true; |
| 138 | + } |
| 139 | + |
| 140 | + @Override |
| 141 | + public String getTipoNotificacion() { |
| 142 | + return "SMS"; |
| 143 | + } |
| 144 | + |
| 145 | + @Override |
| 146 | + public boolean validarDestinatario(String destinatario) { |
| 147 | + return destinatario != null && destinatario.matches("\\+?[0-9]{10,15}"); |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + // ========================================================================== |
| 152 | + // 3. SISTEMA DE NOTIFICACIONES (MÓDULO DE ALTO NIVEL) |
| 153 | + // ========================================================================== |
| 154 | + |
| 155 | + // El sistema depende de la abstracción, NO de implementaciones concretas |
| 156 | + static class SistemaNotificaciones { |
| 157 | + private ServicioNotificacion servicioNotificacion; |
| 158 | + |
| 159 | + // Inyección de dependencia a través del constructor |
| 160 | + public SistemaNotificaciones(ServicioNotificacion servicioNotificacion) { |
| 161 | + this.servicioNotificacion = servicioNotificacion; |
| 162 | + } |
| 163 | + |
| 164 | + // Método para cambiar el servicio en tiempo de ejecución |
| 165 | + public void setServicioNotificacion(ServicioNotificacion servicioNotificacion) { |
| 166 | + this.servicioNotificacion = servicioNotificacion; |
| 167 | + } |
| 168 | + |
| 169 | + // Método principal para enviar notificaciones |
| 170 | + public boolean enviarNotificacion(String destinatario, String mensaje) { |
| 171 | + System.out.println("\n=== SISTEMA DE NOTIFICACIONES ==="); |
| 172 | + System.out.println("Tipo de servicio: " + servicioNotificacion.getTipoNotificacion()); |
| 173 | + |
| 174 | + return servicioNotificacion.enviarNotificacion(destinatario, mensaje); |
| 175 | + } |
| 176 | + |
| 177 | + // Método para enviar notificaciones múltiples |
| 178 | + public void enviarNotificacionMultiple(String[] destinatarios, String mensaje) { |
| 179 | + System.out.println("\n=== ENVÍO MÚLTIPLE ==="); |
| 180 | + System.out.println("Servicio: " + servicioNotificacion.getTipoNotificacion()); |
| 181 | + |
| 182 | + int exitosos = 0; |
| 183 | + for (String destinatario : destinatarios) { |
| 184 | + if (servicioNotificacion.enviarNotificacion(destinatario, mensaje)) { |
| 185 | + exitosos++; |
| 186 | + } |
| 187 | + } |
| 188 | + |
| 189 | + System.out.println("Resumen: " + exitosos + "/" + destinatarios.length + |
| 190 | + " notificaciones enviadas exitosamente"); |
| 191 | + } |
| 192 | + |
| 193 | + // Método para obtener información del servicio actual |
| 194 | + public String getInformacionServicio() { |
| 195 | + return "Servicio actual: " + servicioNotificacion.getTipoNotificacion(); |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + // ========================================================================== |
| 200 | + // 4. FACTORY PARA CREAR SERVICIOS (OPCIONAL) |
| 201 | + // ========================================================================== |
| 202 | + |
| 203 | + static class FactoryNotificaciones { |
| 204 | + |
| 205 | + public static ServicioNotificacion crearServicioEmail(String servidor) { |
| 206 | + return new ServicioEmail(servidor); |
| 207 | + } |
| 208 | + |
| 209 | + public static ServicioNotificacion crearServicioPush(String appId) { |
| 210 | + return new ServicioPush(appId); |
| 211 | + } |
| 212 | + |
| 213 | + public static ServicioNotificacion crearServicioSMS(String proveedor, String apiKey) { |
| 214 | + return new ServicioSMS(proveedor, apiKey); |
| 215 | + } |
| 216 | + } |
| 217 | + |
| 218 | + // ========================================================================== |
| 219 | + // 5. CÓDIGO DE VERIFICACIÓN DEL DIP |
| 220 | + // ========================================================================== |
| 221 | + |
| 222 | + public static void main(String[] args) { |
| 223 | + System.out.println("=== DEMOSTRACIÓN DEL PRINCIPIO DE INVERSIÓN DE DEPENDENCIAS (DIP) ==="); |
| 224 | + |
| 225 | + // 1. Crear servicios específicos |
| 226 | + ServicioNotificacion servicioEmail = new ServicioEmail("smtp.gmail.com"); |
| 227 | + ServicioNotificacion servicioPush = new ServicioPush("com.miapp.notificaciones"); |
| 228 | + ServicioNotificacion servicioSMS = new ServicioSMS("Twilio", "sk_test_123456"); |
| 229 | + |
| 230 | + // 2. Crear sistema de notificaciones con inyección de dependencia |
| 231 | + SistemaNotificaciones sistema = new SistemaNotificaciones(servicioEmail); |
| 232 | + |
| 233 | + System.out.println("\n1. VERIFICANDO CUMPLIMIENTO DEL DIP:"); |
| 234 | + System.out.println("- El SistemaNotificaciones depende de la interfaz ServicioNotificacion"); |
| 235 | + System.out.println("- NO depende de implementaciones concretas"); |
| 236 | + System.out.println("- Las implementaciones dependen de la abstracción"); |
| 237 | + System.out.println("- Se puede cambiar el comportamiento sin modificar el sistema"); |
| 238 | + |
| 239 | + // 3. Probar con diferentes implementaciones |
| 240 | + System.out.println("\n2. PROBANDO CON SERVICIO EMAIL:"); |
| 241 | + sistema. enviarNotificacion( "[email protected]", "Bienvenido a nuestro sistema"); |
| 242 | + |
| 243 | + System.out.println("\n3. CAMBIANDO A SERVICIO PUSH (sin modificar el sistema):"); |
| 244 | + sistema.setServicioNotificacion(servicioPush); |
| 245 | + sistema.enviarNotificacion("token_dispositivo_123456789", "Nueva actualización disponible"); |
| 246 | + |
| 247 | + System.out.println("\n4. CAMBIANDO A SERVICIO SMS:"); |
| 248 | + sistema.setServicioNotificacion(servicioSMS); |
| 249 | + sistema.enviarNotificacion("+1234567890", "Código de verificación: 123456"); |
| 250 | + |
| 251 | + // 4. Demonstrar envío múltiple con diferentes servicios |
| 252 | + String[] emailsDestino = { "[email protected]", "[email protected]", "email_invalido" }; |
| 253 | + String[] telefonos = { "+1234567890", "+0987654321", "telefono_invalido" }; |
| 254 | + String[] tokens = { "token_123", "token_456", "tk_789" }; |
| 255 | + |
| 256 | + System.out.println("\n5. ENVÍO MÚLTIPLE CON EMAIL:"); |
| 257 | + sistema.setServicioNotificacion(servicioEmail); |
| 258 | + sistema.enviarNotificacionMultiple(emailsDestino, "Notificación masiva por email"); |
| 259 | + |
| 260 | + System.out.println("\n6. ENVÍO MÚLTIPLE CON SMS:"); |
| 261 | + sistema.setServicioNotificacion(servicioSMS); |
| 262 | + sistema.enviarNotificacionMultiple(telefonos, "Notificación masiva por SMS"); |
| 263 | + |
| 264 | + System.out.println("\n7. ENVÍO MÚLTIPLE CON PUSH:"); |
| 265 | + sistema.setServicioNotificacion(servicioPush); |
| 266 | + sistema.enviarNotificacionMultiple(tokens, "Notificación masiva PUSH"); |
| 267 | + |
| 268 | + // 5. Demostrar uso del Factory |
| 269 | + System.out.println("\n8. USANDO FACTORY PARA CREAR SERVICIOS:"); |
| 270 | + ServicioNotificacion emailFactory = FactoryNotificaciones.crearServicioEmail("smtp.outlook.com"); |
| 271 | + sistema.setServicioNotificacion(emailFactory); |
| 272 | + sistema. enviarNotificacion( "[email protected]", "Mensaje desde factory"); |
| 273 | + |
| 274 | + // 6. Verificar manejo de errores |
| 275 | + System.out.println("\n9. PROBANDO MANEJO DE ERRORES:"); |
| 276 | + sistema.setServicioNotificacion(servicioEmail); |
| 277 | + sistema.enviarNotificacion("email_sin_arroba", "Este email debería fallar"); |
| 278 | + |
| 279 | + sistema.setServicioNotificacion(servicioSMS); |
| 280 | + sistema.enviarNotificacion("123", "Este SMS debería fallar"); |
| 281 | + |
| 282 | + System.out.println("\n=== VERIFICACIÓN FINAL DEL DIP ==="); |
| 283 | + System.out.println("CUMPLIMIENTO EXITOSO:"); |
| 284 | + System.out.println("- Módulos de alto nivel no dependen de módulos de bajo nivel"); |
| 285 | + System.out.println("- Ambos dependen de abstracciones"); |
| 286 | + System.out.println("- Las abstracciones no dependen de detalles"); |
| 287 | + System.out.println("- Los detalles dependen de abstracciones"); |
| 288 | + System.out.println("- El sistema es extensible sin modificar código existente"); |
| 289 | + System.out.println("- Se puede inyectar cualquier implementación de ServicioNotificacion"); |
| 290 | + |
| 291 | + // Ejemplo de extensibilidad - agregar nuevo servicio sin modificar código |
| 292 | + // existente |
| 293 | + System.out.println("\n10. DEMOSTRANDO EXTENSIBILIDAD:"); |
| 294 | + ServicioNotificacion nuevoServicio = new ServicioNotificacion() { |
| 295 | + @Override |
| 296 | + public boolean enviarNotificacion(String destinatario, String mensaje) { |
| 297 | + System.out.println("SLACK: Enviando a canal " + destinatario + ": " + mensaje); |
| 298 | + return true; |
| 299 | + } |
| 300 | + |
| 301 | + @Override |
| 302 | + public String getTipoNotificacion() { |
| 303 | + return "SLACK"; |
| 304 | + } |
| 305 | + |
| 306 | + @Override |
| 307 | + public boolean validarDestinatario(String destinatario) { |
| 308 | + return destinatario != null && destinatario.startsWith("#"); |
| 309 | + } |
| 310 | + }; |
| 311 | + |
| 312 | + sistema.setServicioNotificacion(nuevoServicio); |
| 313 | + sistema.enviarNotificacion("#general", "Nuevo servicio agregado sin modificar código existente"); |
| 314 | + |
| 315 | + System.out.println("\nSISTEMA COMPLETAMENTE COMPATIBLE CON DIP"); |
| 316 | + } |
| 317 | +} |
0 commit comments