From Head First Design Patterns, p. 139, on the Dependency Inversion Principle:
Dependency Inversion Principle: Depends on abstractions. It does not depend on specific classes.
At first, this principle sounds just like “a program for an interface, not an implementation,” right? It looks like; however, the dependency inversion principle makes an even stronger statement about abstraction. This suggests that our high-level components should not depend on our low-level components; rather, they should depend on abstractions.
A "high level" component is a class with behavior defined in terms of other "low level" components. For example, PizzaStore is a high-level component because its behavior is defined in terms of pizza - it creates all the various pizza objects, cooks, bakes, cuts and places them, and the pizza that it uses is low-level components.
The following code follows the principle of “program for an interface, not an implementation,” because you invoke Bake and Deliver in an abstraction. But this is not consistent with the DI principle, because your first block of code still depends on the specific types of Pizza .
public class PizzaStore { public void OrderPizza(PizzaType type) { Pizza pizza; switch(type) { case PizzaType.FourSeasons: pizza = new FourSeasonsPizza();
Using the factory method template or the abstract factory template, you accomplish both principles. Now you program against abstraction, and you depend only on abstractions. A pizza shop depends on two abstractions: Pizza and PizzaFactory .
public class PizzaStore { private PizzaFactory factory; public PizzaStore(PizzaFactory factory) { this.factory = factory; } public void OrderPizza(PizzaType type) { Pizza pizza = factory.CreatePizza(type);
So, the principle of DI includes the principle of "program for the interface."
dcastro
source share