Inversion of Control Pattern

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

External

Internal

Overview

Dependency injection is a software design pattern that deals with how object instances get created and how they get a hold of their dependencies. There are only three ways a component can get a hold of its dependencies:

  1. The component creates the dependency, typically using the new operator. Not optimal because we need to hardcode details of the dependency.
  2. The component can look up the dependency, for example by referring to a global variable. Not optimal because we need to hardcode details of the dependency.
  3. The component can have the dependency passed to it where it is needed - this is dependency injection.

Definitions

Inversion of Control

The core concept behind IoC is that an object exposes its dependencies via some contract. Dependencies include such things as system resources and essentially anything that an object needs to perform its designated function but is not concerned with its implementation. In a nested object graph, each object in the call chain exposes its dependencies to the outer caller that uses it, who in turn exposes those dependencies including any of its own to its caller and so on, until all dependencies manifest itself at the top. The top-object then assembles the dependency graph before activating the objects. The top-object is generally an entry point into your system such as an application main, Servlet, etc.

Injection IoC

Injection IoC is a popular approach to IoC that advocates that an object expose its dependencies via its constructor or Java bean properties. This popular use of Injection IoC also includes a generic container that manages the overall object graph and the injection of dependencies when an object's life-cycle begins.

Use Cases