I am working on a Spring Boot project where I have a Notifier interface with a send(String message) method. Different implementations of Notifier, such as FCMNotifier and SNSNotifier, require additional parameters to send notifications (e.g., tokens, topics, etc.).
Here is an example of my interface and two implementations:
`public interface Notifier {
void send(String message);
}
@Component
public class FCMNotifier implements Notifier {
@Override
public void send(String message) {
// Use token to send message via FCM
// need token
}
}
@Component
public class SNSNotifier implements Notifier {
@Override
public void send(String message) {
// Use topicArn to send message via SNS
// need topicArn
}
}
`
As you can see, each implementation requires additional parameters (token for FCMNotifier, and topicArn for SNSNotifier). I want to make this design more flexible and avoid tightly coupling the parameters to specific implementations.
My Question:
What is the best way to handle such additional parameters for different implementations in a scalable and maintainable way?
Should I use something like a Context object to pass parameters dynamically? Or are there better design patterns to solve this?
Should I add a builder to handle common requests instead?
I tried using both the Builder pattern and the Decorator pattern to improve flexibility and scalability. I expected the Builder pattern to help in constructing notifications with different parameters (like tokens or topics) dynamically, and the Decorator pattern to allow me to layer additional behaviors (e.g., logging or retry mechanisms) around the notification process. However, I am not sure if this is the right approach or if there are better patterns or practices I should consider for this use case.
KzeroJun is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
Sounds like they don’t have a common interface if additional parameters are needed.
My first thought is: Don’t overcomplicate it.
If you make the common method send()
, without parameters, you can pass the different parameter types into a constructor as member variables. Each type of Notifier
can handle them as they wish.
The downside to this approach is that you need to create an instance every time you want to send a notification.
Java developers love patterns and object hierarchies. Sometimes we get carried away. Do something simple and only add complexity when necessary.