什么是一个好的类比来理解IoC和DI?
什么是一个好的类比来理解IoC和DI?
如果以汽车为经典例子。你可以按照常规的购车流程,使用制造商提供的轮胎:
public class Fifteens
{
public void Roll() { Console.WriteLine("Nice smooth family ride..."); }
}
public class Car
{
Fifteens wheels = new Fifteens();
public Car() { }
public void Drive() { wheels.Roll; }
}
然后:
Car myCar = new Car();
myCar.Drive() // Uses the stock wheels
或者你可以找到一位定制汽车建造师,让他们按照轮毂的规格制作出符合你要求的轮毂,只要它们符合轮毂的规格说明:
public interface IWheel
{
void Roll();
}
public class Twenties : IWheel
{
public void Roll() { Console.WriteLine("Rough Ridin'...");
}
public class Car
{
IWheel _wheels;
public Car(IWheel wheels) { _wheels = wheels; }
public void Drive() { wheels.Roll(); }
}
然后:
Car myCar = new Car(new Twenties());
myCar.Drive(); // Uses the wheels you injected.
但现在你可以注入任何类型的轮子。请记住,这只是一种依赖注入(构造函数注入)的方式,但它是最简单的示例之一。