Skip to content

Instantly share code, notes, and snippets.

@ibayazit
Created November 10, 2023 10:36
Show Gist options
  • Save ibayazit/0efbc3f14f6cd92a13d51f8083d72e1b to your computer and use it in GitHub Desktop.
Save ibayazit/0efbc3f14f6cd92a13d51f8083d72e1b to your computer and use it in GitHub Desktop.
Sample DI
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