// For classes whose modules provide dependencies
@Module
// For the methods within @Module classes
@Provides
// To request a dependency
@Inject
// Bridge between modules and injection
@Component
/**
* Creates the independent class Motor
*/
public class Motor {
private int rpm;
public Motor(){
this.rpm = 0;
}
public int getRpm(){
return rpm;
}
public void accelerate(int value){
rpm = rpm + value;
}
public void brake(){
rpm = 0;
}
}
/**
* Creates the dependent class Vehicle
*/
public class Vehicle {
private Motor motor;
public Vehicle(Motor motor){
this.motor = motor;
}
public void increaseSpeed(int value){
motor.accelerate(value);
}
public void stop(){
motor.brake();
}
public int getSpeed(){
return motor.getRpm();
}
}
/**
* Create a module that will define how to
* provide the objects you will need
*/
@Module
public class VehicleModule {
@Provides @Singleton
Motor provideMotor(){
return new Motor();
}
@Provides @Singleton
Vehicle provideVehicle(){
return new Vehicle(new Motor());
}
}
/**
* Just request a dependency on a dependent object by
* using the @Inject annotation on a constructor, field or method.
*/
@Inject
public Vehicle(Motor motor){
this.motor = motor;
}
/**
* Use a component interface to connect @Modules and @Inject
*/
@Singleton
@Component(modules = {VehicleModule.class})
public interface VehicleComponent {
Vehicle provideVehicle();
}
/**
* Use the component interface to get the
* dependencies.
*/
public Vehicle vehicle;
protected void onCreate() {
VehicleComponent component = Dagger_VehicleComponent.builder().vehicleModule(new VehicleModule()).build();
vehicle = component.provideVehicle();
}