Dependency injection

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
(New page: Dependency injection separates behaviour from dependency resolution. It is an alternative to the Factory pattern and hard coded dependencies. === Three examples of managing dependencies =...)
 
m
Line 1: Line 1:
Dependency injection separates behaviour from dependency resolution. It is an alternative to the Factory pattern and hard coded dependencies.
+
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.
  
 
=== Three examples of managing dependencies ===
 
=== Three examples of managing dependencies ===

Revision as of 12:46, 30 August 2009

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.

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