Skip to main content

Dependency Injection

CreationalDecouplingAbout 1 min


Dependency Injection is a software design pattern in which one or more dependencies (or services)
are injected, or passed by reference, into a dependent object (or client) and are made part of the
client's state. The pattern separates the creation of a client's dependencies from its own behavior,
which allows program designs to be loosely coupled and to follow the inversion of control and single
responsibility principles.


Real world example

The old wizard likes to fill his pipe and smoke tobacco once in a while. However, he doesn't want
to depend on a single tobacco brand only but likes to be able to enjoy them all interchangeably.

In plain words

Dependency Injection separates creation of client's dependencies from its own behavior.

Wikipedia says

In software engineering, dependency injection is a technique in which an object receives other
objects that it depends on. These other objects are called dependencies.

Programmatic Example

Let's first introduce the Tobacco interface and the concrete brands.

public abstract class Tobacco {

  public void smoke(Wizard wizard) {"{} smoking {}", wizard.getClass().getSimpleName(),

public class SecondBreakfastTobacco extends Tobacco {

public class RivendellTobacco extends Tobacco {

public class OldTobyTobacco extends Tobacco {

Next here's the Wizard class hierarchy.

public interface Wizard {

  void smoke();

public class AdvancedWizard implements Wizard {

  private final Tobacco tobacco;

  public AdvancedWizard(Tobacco tobacco) {
    this.tobacco = tobacco;

  public void smoke() {

And lastly we can show how easy it is to give the old wizard any brand of tobacco.

    var advancedWizard = new AdvancedWizard(new SecondBreakfastTobacco());

Class diagram

alt text
Dependency Injection


Use the Dependency Injection pattern when:

  • When you need to remove knowledge of concrete implementation from object.
  • To enable unit testing of classes in isolation using mock objects or stubs.