This is an old revision of the document!
https://google.github.io/dagger/
Dagger 공식 홈에 있는 CoffeeMaker 예제 단순화.
커피 머신이 작동하려면 커피 물을 끓일 Heater, 달여진 커피를 받을 Pump가 필요.
public interface Heater {
void on();
void off();
boolean isHot();
}
public class MyHeater implements Heater {
private boolean heating;
public void on() {
System.out.println("~ ~ ~ heating ~ ~ ~");
this.heating = true;
}
public void off() {
this.heating = false;
}
public boolean isHot() {
return heating;
}
}
public interface Pump {
void pump();
}
public class MyPump implements Pump {
private final Heater heater;
@Inject
public MyPump(Heater heater) {
this.heater = heater;
}
public void pump() {
if (heater.isHot()) {
System.out.println("=> => pumping => =>");
}
}
}
각 함수에 “provide” 접두사를 붙인다.
@Module
public class CoffeeMakerModule {
@Provides
Heater provideHeater() {
return new MyHeater();
}
@Provides
Pump providePump(MyPump pump) {
return pump;
}
}
public class CoffeeMaker {
@Inject
Heater heater;
@Inject
Pump pump;
@Inject
public CoffeeMaker(Heater heater, Pump pump){
this.heater = heater;
this.pump = pump;
}
public void brew(){
heater.on();
pump.pump();
System.out.println("brew!");
heater.off();
}
}
@Component(modules = CoffeeMakerModule.class)
public interface CoffeeComponent {
CoffeeMaker maker(); // getter 작성
}