I'm currently implementing the factory design pattern in Angular, but I feel like I might be missing something or perhaps there's a more efficient approach. My current setup involves a factory that returns a specific car class based on user input (e.g., selecting "Mazda" will return an instance of the Mazda class, while choosing "Ford" will return an instance of the Ford class). Each car class relies on multiple services.
constructor(
private userService: UserService,
private logService: LogService
) {}
create(
info
):
| Mazda
| Tesla
| Ford
switch (info.type) {
case 'mazda':
return new Mazda(info, this.userService, this.logService);
case 'tesla':
return new Tesla(info, this.userService, this.logService);
case 'ford':
return new Ford(info, this.userService, this.logService);
}
}
}
The issue arises when setting up the factory within a component, as it requires injecting the dependencies.
this.carFactory = new CarFactory(this.userService, this.logService);
It feels odd that my component needs to be aware of the dependencies required by the factory. Is there a way to establish a factory in Angular without having to pass the dependencies during instantiation? Perhaps something like
this.carFactory = new CarFactory();