Dependency Injection: Difference between revisions
Jump to navigation
Jump to search
Line 13: | Line 13: | ||
engine = new Engine() | engine = new Engine() | ||
wheels = new Wheels() | wheels = new Wheels() | ||
} | |||
void drive() { | |||
// chug chug | |||
} | |||
} | |||
</syntaxhighlight> | |||
<br> | |||
For Dependency Injection we can provide the '''prebuilt''' wheels and engine via the constructor | |||
<syntaxhighlight lang="kotlin" highlight="5,6,7,8"> | |||
class Car { | |||
Engine engine | |||
Wheels wheels; | |||
Car(Engine engine, Wheels wheels) { | |||
this.engine = engine | |||
this.wheels = wheels | |||
} | } | ||
Revision as of 01:18, 1 February 2021
Introduction
Dependency Injection or DI is when we provides the things we need into another object.
Originally in OO is was thought better to hide the internal objects and create them inside the object.
class Car {
Engine engine
Wheels wheels;
Car() {
engine = new Engine()
wheels = new Wheels()
}
void drive() {
// chug chug
}
}
For Dependency Injection we can provide the prebuilt wheels and engine via the constructor
class Car {
Engine engine
Wheels wheels;
Car(Engine engine, Wheels wheels) {
this.engine = engine
this.wheels = wheels
}
void drive() {
// chug chug
}
}