Our Angular application has a service which can have different implementations, aka. “strategies”. For simplicity, let’s assume it’s an “event reporting” service. The event reporting service has a function for reporting information. Depending on a runtime preference, the reporting can either turned off, go to the console
, or be sent to a REST API, or go somewhere else.
Using pure TS, this would look like:
interface IReporter {
report (message: string): void;
}
class NoReporter implements IReporter {
report (message: string): void {
// no op.
}
}
class ConsoleReporter implements IReporter {
report (message: string): void {
console.log(message);
}
}
// etc.
In a consumer, I’d put some factory which delivers the desired reporter, e.g. based on a user-preference setting:
getReporter (key: string): IReporter {
switch (key) {
// … tedious cases, which need to be mainted. Yikes!
}
}
However, this feels not very “Angular”-like. First step would probably be to make proper Angular services of the individual reporters, but this alone feels like little gained. So: Is there some existing mechanism which would give me above factory functionality to dynamically look up an implementation? Any patterns, example or best practices to follow?