Looking at object dependencies
When you directly instantiate an object, you are depending on its
concrete class. Take a look at our very dependent PizzaStore one
page back. It creates all the pizza objects right in the PizzaStore class
instead of delegating (phân quyền) to a factory.
If we draw a diagram representing that version of the PizzaStore
and all the objects it depends on, here’s what it looks like:
The Dependency Inversion Principle
It should be pretty clear that reducing dependencies to
concrete classes in our code is a “good thing.” In fact, we’ve
got an OO design principle that formalizes this notion; it even
has a big, formal name: Dependency Inversion Principle
Depend upon abstractions. Do not depend upon concrete classes
=> Applying the principle for PizzaStore
Factory Method allows us to do just that.
So after we’ve applied the Factory Method , out diagram looks like this:
A few guidelines to help you follow the Principle…
The following guidelines can help you avoid OO designs that violate the Dependency Inversion Principle:
- //If you use new, you’ll be holding a reference to a concrete class. Use a factory to get around that!
- No variable should hold a reference to a concrete class.
- //If you derive from a concrete class, you’re depending on a concrete class. Derive from an
- // abstraction, like an interface or an abstract class
- No class should derive from a concrete class
- // If you override an implemented method, then your base class wasn’t really an abstraction to start
- //with. Those methods implemented in the base class are meant to be shared by all your subclasses.
- No method should override an implemented method of any of its base classes.