Home >Backend Development >C++ >How Can I Effectively Manage Excessive Dependencies in a Parameterized Factory Method?
Factory method using dependency injection and control inversion
You are familiar with factory methods and the dependency injection (DI) pattern, but need guidance for the specific case of a large number of dependencies in a parameterized factory method.
Problem: Over-reliance on parameterized factories
In your factory class, the constructor requires six dependencies, and each car instance created by the factory has a different set of dependencies. This makes the factory difficult to manage and introduces CreateCar
statements in switch case
methods.
Alternative methods
You proposed two alternatives: injecting the car instance directly into the factory constructor or using a service locator. However, these solutions each have their drawbacks. Injecting car instances violates factory design principles, and using service locators is generally discouraged.
Solution: Strategy Pattern for Dependency Injection
Instead of using switch case
statements in factories, consider adopting the Strategy pattern for dependency injection. This pattern allows you to create multiple factory implementations, each dedicated to creating a specific type of car.
Implementation:
ICarFactory
and ICarStrategy
. ICarFactory
represents a factory used to create car instances, while ICarStrategy
represents a collection of factories. Car1Factory
and Car2Factory
. These factories inject necessary dependencies through their constructors. CarStrategy
class that implements ICarStrategy
and contains an array of ICarFactory
instances. The CarStrategy
method in CreateCar
iterates over the factories to find a factory that can create the requested car type. CarStrategy
instances into your code. You can then use the CreateCar
method to instantiate the car instance without specifying the dependencies directly. Advantages of Strategy Mode:
switch case
statements in factory methodsThe above is the detailed content of How Can I Effectively Manage Excessive Dependencies in a Parameterized Factory Method?. For more information, please follow other related articles on the PHP Chinese website!