8bitzz / blogs

0 stars 0 forks source link

Dependency Injection #7

Closed 8bitzz closed 3 years ago

8bitzz commented 3 years ago

What are design patterns?

Why should we use design patterns?

Scenario

Given a class A which needs to use an instance of class B. How do you implement this idea without creating a direct dependency between 2 classes?

Dependency Injection

The 4 Roles in Dependency Injection

  1. The service (B) you want to use.
  2. The client (A) that uses the service.
  3. An interface that’s used by the client (A) and implemented by the service (B).
  4. The injector which creates a service instance (B) and injects it into the client (A).

Code example with Spring framework

Quick Recap

Traditional Approach --> need to instantiate an implementation of the Item interface within the Store class itself.

public class Store {
    private Item item;

    public Store() {
        item = new ItemImpl1();    
    }
}

DI Approach --> no need to specify the implementation of the Item that we want:

public class Store {
    private Item item;
    public Store(Item item) {
        this.item = item;
    }
}

The Interface represents the IoC container

DI can be done through constructors, setters or fields