The difference between “depends on abstractions of non-specific classes” and “from program to interface”,

The difference between these two principles is not clear to me. They just look like the same thing.

What is the difference?

+7
oop design-principles
source share
2 answers

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(); //... } //do something with pizza pizza.Bake(); pizza.Deliver(); } } 

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); //do something with pizza pizza.Bake(); pizza.Deliver(); } } 

So, the principle of DI includes the principle of "program for the interface."

+4
source share

In the GoF Patterns book you can find the definition of “interface”. The set of all signatures defined by object operations is called the interface to the object. The interfaces in this book were declared in .h files and separated from the implementation. So, these principles are synonymous.

.NET developers new to the GoF Patterns book may be confused . NET interfaces .

-2
source share

All Articles