Help me understand one nuance related to DI
-
Considering that such Dependency Injection (DI) I drew an article in WIKI https://ru.wikipedia.org/wiki/%D0%92%D0%BD%D0%B5%D0%B4%D1%80%D0%B5%D0%BD%D0%B8%D0%B5_%D0%B7%D0%B0%D0%B2%D0%B8%D1%81%D0%B8%D0%BC%D0%BE%D1%81%D1%82%D0%B8 ♪
Transmitted the C# example, and I got the next DI implementation.
Question: Why is this implementation class
CarFactory
? What is this and why is it necessary? What are you using?Interfaces
interface IEngine { int getEngineRotation(); void setFuelConsumptionRate(int FUEL_FLOW); }
interface ICar
{
int getSpeed();
void setPedalPressure(int PEDAL_PRESSURE);
}
Implementation
class Engine : IEngine
{
int engineRotation = 0;public int getEngineRotation() { return engineRotation; } public void setFuelConsumptionRate(int FUEL_FLOW) { engineRotation = FUEL_FLOW; } }
class Car : ICar
{
private IEngine _engine;public Car(IEngine engine) { _engine = engine; } public int getSpeed() { return _engine.getEngineRotation() * 10; } public void setPedalPressure(int PEDAL_PRESSURE) { _engine.setFuelConsumptionRate(PEDAL_PRESSURE * 2); }
}
Use
class CarFactory
{
public static ICar buildCar()
{
return new Car(new Engine());
}
}class Program
{
static void Main(string[] args)
{
ICar newCar = CarFactory.buildCar();
newCar.setPedalPressure(5);
int speed = newCar.getSpeed();
Console.WriteLine("Speed of the car is " + speed);
}
}
-
In the context of DI, this code demonstrates the introduction logic through the design (constructor injection) IEngine in Car in a separate class - factory. Thus, different types of engine can be used in the main programme without altering the Car and Program by only changing the CarFactory code.
The flexibility of this approach is limited compared with the introduction of the DI-container, but is entitled to exist.