I am learning about the bridge Pattern using Spring boot and I’m using Chatgpt to help me with the process but I can’t understand how it knows when it needs to use EmailSender in EmailNotification and SmsSender in SmsNotification in the example it’s giving me. I get confused by the fact that both beans EmailSender and SmsSender are configured to return the Sender type plus EmailNotification and SmsNotification both also have the type Sender in their constructor.
So, how do they know which Sender they both have to use? This is the code I’m trying to understand.
// Notification.java
public abstract class Notification {
protected Sender sender;
protected Notification(Sender sender) {
this.sender = sender;
}
public void notifyUser(String message) {
sender.send(formatMessage(message));
}
protected abstract String formatMessage(String message); // Método abstracto para formatear el mensaje
}
// EmailNotification.java
public class EmailNotification extends Notification {
public EmailNotification(Sender sender) {
super(sender);
}
@Override
protected String formatMessage(String message) {
return "Email Notification: " + message;
}
}
// SmsNotification.java
public class SmsNotification extends Notification {
public SmsNotification(Sender sender) {
super(sender);
}
@Override
protected String formatMessage(String message) {
return "SMS Notification: " + message;
}
}
@Configuration
public class AppConfig {
@Bean
public Sender emailSender() {
return new EmailSender();
}
@Bean
public Sender smsSender() {
return new SmsSender();
}
@Bean
public Notification emailNotification(Sender emailSender) {
return new EmailNotification(emailSender);
}
@Bean
public Notification smsNotification(Sender smsSender) {
return new SmsNotification(smsSender);
}
}
@RestController
@RequestMapping("/notifications")
public class NotificationController {
private final Notification emailNotification;
private final Notification smsNotification;
@Autowired
public NotificationController(Notification emailNotification, Notification smsNotification) {
this.emailNotification = emailNotification;
this.smsNotification = smsNotification;
}
@GetMapping("/email")
public ResponseEntity<String> sendEmailNotification() {
emailNotification.notifyUser("Hello via Email!");
return ResponseEntity.ok("Email notification sent!");
}
@GetMapping("/sms")
public ResponseEntity<String> sendSmsNotification() {
smsNotification.notifyUser("Hello via SMS!");
return ResponseEntity.ok("SMS notification sent!");
}
}
Thanks!