Dependency Injection:
- DI is a technique where 1object (or static method) supplies dependencies for other objects.i.e. Passing the service to the client, rather than client building the service himself.
- It is done so that your code can be re-used and can be loosely coupled.
The intent behind the DI is to de-couple objects to an object to an extent, such that no other client code had to be changed simply because object needs to be changed to diff. one
Advantages:
- DI allows concurrent or Independent development
- Decrease coupling between the class & dependency
There are 3 types in which DI can be achieved:
1. Constructor Injection: Dependencies are provided through class Constructor.
2. Setter Injection: Client exposes the setter method() , so that the injector injects the dependencies
3. Interface Injection: Client must implement that expose the setter() that accept dependency
Constructor Injection :
Public class Client {
// Constructor
Client(Service service){
This.service= service;
}
}
Setter Injection :
Public class Client {
public void serService(Service service){
This.service= service;
}
}
Interface Injection :
Public interface Client {
Public void setService(Service service);
}
Steps to Design DI:
1. Design interfaces
2. Don’t use classes to call other class, instead use dependencies
3. Don’t create objects, set it NULL
4. Move objects to the class level
5. Create Getters & Setters
Eg:
Public interface test { // 1
Void add(int I, int j);
}
Public class TestClass implements test {
Test obj= new test(); // Do not do this, instead follow next step
Test obj= null // 3
Public static void main(String [] args)
{
Int sum= obj.add(1,2);
System.out.println(sum);
}
//Getter & Setters //5
}
No comments:
Post a Comment