Home >Backend Development >C++ >How Can Dependency Injection Solve Factory Method Challenges with Many Dependencies?
Question:
You are familiar with the factory method pattern, but face challenges in managing a large number of dependencies in the factory constructor. You try to inject a concrete car class into the factory, but this violates the factory principle. You also don't want to use the service locator because it's known for being an anti-pattern.
Solution:
The most suitable method for this scenario is Strategy Mode. This pattern allows your DI containers to inject dependencies into factory instances that belong to them, eliminating the need to use service locators or clutter other classes with dependencies.
Interface:
<code>public interface ICarFactory { ICar CreateCar(); bool AppliesTo(Type type); } public interface ICarStrategy { ICar CreateCar(Type type); }</code>
Factory:
<code>public class Car1Factory : ICarFactory { private readonly IDep1 dep1; private readonly IDep2 dep2; private readonly IDep3 dep3; // ... 构造函数和实现 } public class Car2Factory : ICarFactory { private readonly IDep4 dep4; private readonly IDep5 dep5; private readonly IDep6 dep6; // ... 构造函数和实现 }</code>
Strategy:
<code>public class CarStrategy : ICarStrategy { private readonly ICarFactory[] carFactories; public CarStrategy(ICarFactory[] carFactories) { // ... 构造函数和实现 } }</code>
Usage:
<code>var strategy = new CarStrategy(new ICarFactory[] { new Car1Factory(dep1, dep2, dep3), new Car2Factory(dep4, dep5, dep6) }); var car1 = strategy.CreateCar(typeof(Car1)); var car2 = strategy.CreateCar(typeof(Car2));</code>
Advantages:
The above is the detailed content of How Can Dependency Injection Solve Factory Method Challenges with Many Dependencies?. For more information, please follow other related articles on the PHP Chinese website!