I'm working in a real-time project. They are using 3 tier architecture using interfaces but I am not getting how it will work as Dependency injection. I know interfaces can be multiply-inherited and have some theoretical knowledge. I need a brief discussion about how interfaces can be used in a real-time context.

有帮助吗?

解决方案

For your purposes, think of dependency injection as handing a class the objects it depends on through its constructor.

To avoid tight coupling with the dependencies you pass in, the parameters to your constructor should be interfaces. That way, you can pass in whatever implementation you want, so long as it conforms to the interface you specified.

Example (in Java):

public interface Soundable {
  void makeNoise();
} 

public class OogaHorn implements Soundable {
  public void makeNoise() {
    System.out.println("OOGA!");
  }
}

public class WimpyHorn implements Soundable {
  public void makeNoise() {
    System.out.println("Beep!");
  }
}

public class Car {
  Soundable horn;

  public Car(Soundable s) {
    horn = s;
  }

  public void SoundHorn() {
    horn.makeNoise();
  }
}

class Main {
  public static void main(String[] args) {

    Soundable horn = new OogaHorn(); // Specify which horn you want here.
    Car car = new Car(horn);

    car.SoundHorn(); // OOGA!
  }
}
许可以下: CC-BY-SA归因
scroll top