Created
June 28, 2024 16:30
-
-
Save nikolovlazar/5e84aa85a77ee2837740bbc005f3fe3c to your computer and use it in GitHub Desktop.
Service Locator pattern in TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { CollectionsRepository } from '../repositories/collectionsRepository' | |
import { AuthenticationService } from './authenticationService' | |
import { CollectionsService } from './collectionsService' | |
export class ServiceLocator { | |
private static _cache: Record<string, any> | |
static { | |
console.log('Setting up cache') | |
ServiceLocator._cache = {} | |
} | |
static getService(name: string) { | |
const service = this._cache[name] | |
if (!!service) { | |
console.log(`${name} service is cached! Returning the cached version.`) | |
return service | |
} | |
console.log(`Creating and caching ${name} service...`) | |
if (name === AuthenticationService.name) { | |
// Note: the place to instantiate different repositories if needed | |
const authenticationService = new AuthenticationService() | |
this._cache[name] = authenticationService | |
return authenticationService | |
} | |
if (name === CollectionsService.name) { | |
// Note: the place to instantiate different repositories if needed | |
const collectionsRepository = new CollectionsRepository() | |
const collectionsService = new CollectionsService(collectionsRepository) | |
this._cache[name] = collectionsService | |
return collectionsService | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment