Dependency Injection
What is Dependency Injection?
Each Object-oriented application consists of many classes that work together in order to solve a problem. However, when writing a complex application, application classes should be as independent as possible. DI helps in gluing these classes together and at the same time keeping them independent. Dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object.
Pros
- increase the possibility to reuse classes
- test them independently of other classes while unit testing
Code with no DI vs code with DI
public class Computer {
private CPU cpu;
public Computer() {
this.cpu = new CPU();
}
}
Dependency between Computer and CPU.
public class Computer {
private CPU cpu;
public Computer(CPU cpu) {
this.cpu = cpu;
}
}
Dependency between Computer and CPU. Dependency is injected through class constructor (Computer should not worry about CPU implementation).
Types of DI
- Constructor-based dependency injection – used for mandatory dependencies
public Computer(CPU cpu) {
this.cpu = cpu;
}
- Setter-based dependency injection – used for optional dependencies
public Computer(CPU cpu) {
this.cpu = cpu;
}
- Property-based dependency injection – considered as bad practice!
@Autowired
private CPU cpu;
Letzte Beiträge
Share :
Share :
Weitere Beiträge
View in the MVVM architecture
The View component in the MVVM architecture are the UI controllers – Activities and Fragments. They should be as free as possible from any business logic. Their role is to present the data, not to transform it.
View Model. Example
In this article we will go through the steps of creating a simple game screen. We will make it the traditional way without using View Model and we will see why it is absolutely wrong to persist data in the View.
LiveData
LiveData is an observable data holder class. It is also lifecycle-aware, which means that it respects the lifecycle of the other app components, such as activities, fragments and services. It notifies only active observers, represented by the Observer class.