public class SpellChecker {
private final Lexicon dictionary =...;
private SpellChecker() {} // 객체 생성 방지
public static boolean isValid(String word) { ... }
public static List<String> suggestions(String typo) { ... }
}
public class SpellChecker {
private final Lexicon dictionary = ...;
private Spellchecker(...) {}
public static SpellChecker INSTANCE = new pellChecker(...);
public boolean isValid(String word) { ... }
public List<String> suggestions(String typo) { ... }
}
public class SpellChecker {
private final Lexicon dictionary;
public SpellChecker(Lexicon dictionary) {
}
인스턴스를 생성할 때 생성자에 필요한 자원을 넘겨주는 방식
자원의 수나 의존관계와 무관하게 작동
불변을 보장, 동일 자원 공유를 안전하게 할 수 있음
생성자, 정적 팩터리, 빌더 모두에 적용 가능한 방법
변형: 생성자에 자원 팩터리를 넘겨주는 방식
Mosaic create(Supplier<? extends Tile> tileFactory) {...}
단, 의존성이 많은 프로젝트에서는 코드를 어지럽힐 수 있다: 의존 객체 주입 프레임워크를 사용하여 해결하라
의문사항: 왜 싱글톤을 사용해서 안 되나? 싱글톤에 DI 사용하면 되지 않나(스프링의 경우)?