public class SampleController {
private Repository repository;
public SampleController() {
//this.repository = new HelloRepository();
this.repository = new HiRepository();
}
public void addSample(String sample) {
repository.save(sample);
}
...
}
SampleController
public class SampleController {
private Repository repository;
public SampleController(Repository repository) {
this.repository = repository;
}
public void addSample(String sample) {
repository.save(sample);
}
...
}
SampleController
어떤 Repository가 올지 SampleContoller는 관심이 없다.
외부에서 결정되어 주입되는 Repository를 사용하면 된다.
SampleController는 로직에만 집중할 수 있다.
내부에서 의존하지 않고 외부에 의해 결정되는(제어가 역전된 상황) 이 상황을 의존성 역전이라고 한다.
외부 코드는 다음과 같이 만들어질 것이다.
public class SampleConfig {
public Repository repository() {
return new HiRepository();
// return new HelloRepository();
}
}