Created
November 10, 2023 10:36
-
-
Save ibayazit/0efbc3f14f6cd92a13d51f8083d72e1b to your computer and use it in GitHub Desktop.
Sample DI
This file contains 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
const UserTypes = Object.freeze({ | |
DEFAULT: "DEFAULT", | |
MANAGER: "MANAGER", | |
ADMIN: "ADMIN", | |
}); | |
class DefaultService { | |
run() { | |
console.log(DefaultService.name); | |
} | |
} | |
class ManagerService { | |
run() { | |
console.log(ManagerService.name); | |
} | |
} | |
class AdminService { | |
run() { | |
console.log(AdminService.name); | |
} | |
} | |
class UserStrategySelector { | |
strategies = new Map(); | |
constructor() { | |
this.addStrategy(UserTypes.DEFAULT, DefaultService); | |
this.addStrategy(UserTypes.MANAGER, ManagerService); | |
this.addStrategy(UserTypes.ADMIN, AdminService); | |
} | |
addStrategy(transportType, strategy) { | |
this.strategies.set(transportType, strategy); | |
} | |
getStrategy(transportType) { | |
const strategy = this.strategies.get(transportType); | |
if (!strategy) { | |
throw new Error(`Strategy for ${transportType} not found`); | |
} | |
return new strategy(); | |
} | |
} | |
const userService = new UserStrategySelector(); | |
userService.getStrategy(UserTypes.MANAGER).run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment