0 day streak
javascript / intermediate
Snippet

Polymorphic Notification Services via Dependency Injection

Polymorphism enables interchangeable service implementations. By defining an abstract base class with a contract and injecting subclass instances into Vue components, you can swap implementations (e.g., Toast, Modal, or Console notifiers) without modifying consuming components.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import { provide, inject } from 'vue';
const SERVICE_KEY = Symbol('NotificationService');
class BaseNotifier {
notify(message) {
throw new Error('Method not implemented');
}
}
class ToastNotifier extends BaseNotifier {
notify(message) {
console.log(`[TOAST UI]: ${message}`);
}
}
export function provideNotifier(notifierInstance) {
if (!(notifierInstance instanceof BaseNotifier)) {
throw new TypeError('Invalid notifier implementation');
}
provide(SERVICE_KEY, notifierInstance);
}
export function useNotifier() {
return inject(SERVICE_KEY, new ToastNotifier());
}
vue
Breakdown
1
class BaseNotifier {
Defines an abstract base class defining the required contract.
2
class ToastNotifier extends BaseNotifier {
Implements the concrete notification behavior by overriding the method.
3
if (!(notifierInstance instanceof BaseNotifier)) {
Enforces type compliance to ensure the injected object adheres to the class hierarchy.
4
return inject(SERVICE_KEY, new ToastNotifier());
Injects the provided notifier instance or defaults to a fallback subclass instance.