Dependency injection
From CSSEMediaWiki
Revision as of 12:39, 30 August 2009 by BenMcDonald (Talk | contribs)
Dependency injection 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.