Design Patterns: Dependency Injection

What Dependency Injection is. Let’s imagine an object that does a specific function. Now let’s imagine a second object that takes the first object as an argument. This object cannot function or can function partially without the first one. When this happens, it’s called Dependency Injenction.

Dependency Injection is a design pattern and we want to use it when an object is dependent on another object. Doing that, we are able to enhance our code with new functionalities without changing the existing code. So, our code is maintainable and extendable while allowing our programme to be loosely coupled.

There are 3 ways to perform a dependency injection.

The first one is called Constructor Injection. In this case, class takes the dependent object through the constructor.

Sample Code:

Next is Setter Injection. In this case, class that needs an external object to work takes it from a setter method. Thus, we can pass the dependent object as an argument only if there is a need for that. Dependency Injection is optional in this case.

Sample Code:

Third one is called Interface Injection. In this case we create an interface class that has a function which takes as argument an object.

Sample Code:

Sample Code

It would be better if we continued with an example on how to use dependency injection.

We are going to create a character for a game who is modular and we can change various things like hair color, t-shirts, head size etc. In our case we will see only the head size as an example. So, the user will be able to change the character’s head to a big one or a regular one.

Let’s start with our interface class which is named Head.

The next two classes will implement Head interface creating either a big head or a regular head.

Next step is to create a player who is going to take an object of BigHead or RegularHead classes as an argument.

Let’s start with Player interface.

The class above implements Player interface and it creates a player either with a big head or with a regular one, depending on the class that it will take as an argument.

Finally, we will create one more interface that we will use in order to implement Dependency Injection.

As we can see, each one of two classes above creates a Player object depending on the argument.

The last method does a print in our screen.

Output:
Hi, I am the player with a big head !
Hi, I am the player with a regular head !

 
You can download the source code from GitHub.

Some Other Useful Resources

http://fabien.potencier.org/what-is-dependency-injection.html
https://www.martinfowler.com/articles/injection.html
http://www.procata.com/talks/phptek-may2007-dependency.pdf
http://www.javacreed.com/why-should-we-use-dependency-injection/
http://tutorials.jenkov.com/dependency-injection/dependency-injection-containers.html