I am trying to implement a NotificationService
in a correct way from the point of view of OOP. For this I have the next interface:
abstract class NotificationsService {
void initNotificationsHandlers();
int sendGeneralNotification({String? title, String? body});
//...
}
And his subclass:
class FirebaseNotificationService extends NotificationsService {
//All implementations...
}
The problem is when I implement it. I have to instance it on the main:
NotificationsService notificationsService = new FirebaseNotificationService();
But I have to use this service in more classes,and I don't want to instance the FirebaseNotificationService
in every class because I would be violating the Dependency Inversion Principle. I want other classes just know the abstraction NotificationsService
.
I have thought using something like this:
abstract class NotificationsService {
///Current notification service subclass used.
static final NotificationsService instance;
//...
}
And then implementing the class this way:
Main
NotificationsService.instance = new FirebaseNotificationService();
Other class
NotificationsService.instance.initNotificationsHandlers(); // For example, it could be any method
But it doesn't look very clean because I am using the NotificationService
interface to "save" the current subclass. I think it shouldn't be his responsibility.
Maybe should I make another class which "saves" the current implementation? Or apply a singleton pattern? What is the OOP most correct way to do this?
Clarification: I am not asking for a personal opinion (otherwise this question should be close). I'm asking about the correct OOP solution.
CodePudding user response:
In which language are you programming? Java probably, by reading your Code.
What you actually want is Dependency Injection and a Singleton (even though I think that Singleton is overkill for a NotificationService)
If we remain at the Java Standard, it works in this way:
The classes that need your NotificationService would have a constructor annotated with @Inject and an agument of type NotificationService (not your Implementation Class) - so your consumer classes rely on something abstract rather than something concrete, which makes it easier to change the implementation.
The Dependency Injection Container or Framework would take care that when your classes are being injected by them self somewhere, that their Dependencies are being satisfied in order to be able to construct this class.
How does it actually know which Implementation belongs to an Interface?
Well it depends on the Framework or Platform you are using but you either define your bindings of the interface to the concrete class or is is looking it up with reflection (if we are using Java)
If a class gets injected with a new Instance every time or always the same instance this depends on your annotations on the class itself. For example you could annotate it with @Singleton.
I hope it helps a bit.