Object dependencies


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:

d1

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

Design 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:

d1

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.
  1. //If you derive from a concrete class, you’re depending on a concrete class. Derive from an
  2. // abstraction, like an interface or an abstract class
  3. 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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: