Dependency injection

From CSSEMediaWiki
Revision as of 05:07, 14 October 2009 by JaninaVoigt (Talk | contribs)
Jump to: navigation, search

In the Dependency Injection pattern an object's dependencies are provided externally. This separates behaviour from dependency resolution. It is an alternative to the Factory pattern and hard coded dependencies. It can be interpreted as a more general concept which can be used to describe the purpose of factories or other similar techniques for decoupling.

Participants

This design pattern can arise in a few different forms, but there are generally three participants.

  • Dependent: An object that is expected to perform some task
  • Dependencies: The object(s) that the dependent relies on to perform some task
  • Injector: Composes the dependent with its dependencies so it is ready to use

The injector (also known as a provider or container) handles all issues associated with composing these objects and managing them throughout their life cycle. This includes when and how they are instantiated and disposed of. The injector can be implemented as a abstract factory or service locator.

Three examples of managing dependencies

A dependency hard coded into an object:

class SimpleCar implements Car
   protected final Engine engine = new SimpleEngine()

   public accelerate()
       engine.setFuelValveIntake(gasPedalPressure)
   

Dependency from Factory pattern:

class SimpleCar implements Car
   public accelerate()
       engine = Factory.getEngine()
       engine.setFuelValveIntake(gasPedalPressure)

Dependency Injection:

class SimpleCar implements Car
   protected final Engine engine

   public Car(Engine engine)
      this.engine = engine

   public accelerate()
       engine.setFuelValveIntake(gasPedalPressure)

There are frameworks in all major languages for dependency injection. These frameworks let dependencies be defined with additional language syntax so that the framework can manage the dependencies.

Personal tools