<aside> 📎 ITEM5 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라
</aside>
클래스와 자원
사전
객체에 의존한다. (사전에 존재하는 단어가 아니면 밑줄)하나 이상의 자원에 존재하는 클래스(1) : 맞춤법 검사기의 잘못된 구현 방식
public class SpellChecker {
private static final Lexicon dictionary = ... ;
private SpellChecker() {} // 객체 생성 방지용 생성자
public static boolean isValid(String word) { ... }
}
public class SpellChecker {
private final Lexicon dictionary = ... ;
public static SpellChecker INSTANCE = new SpellChecker();
private SpellChecker() {}
public static boolean isValid(String word) { ... }
}
위의 두가지 방식은 클래스가 단 하나의 사전 객체에만 의존한다고 가정하고 있다 BAD
제안) final 한정자를 제거하고, 다른 사전으로 교체하는 메서드를 추가?
public class SpellChecker {
private static Lexicon dictionary = ...;
public static SpellChecker INSTANCE = new SpellChecker();
private SpellChecker() {}
public static boolean isValid(String word) { ... }
public static void changeDictionary(Lexicon new) { dictionary = new; }
}
의존 객체 주입 방법
public class SpellChecker {
private final Lexicon dictionary;
public SpellChecker(Lexicon dictionary){
this.dictionary = Objects.requireNonNull(dictionary);
}
public boolean is Valid(String word) { ... }
}
public class KoreanDict implements Lexicon { ... }
public class EnglishDict implements Lexicon { ... }
Lexicon kordict = new KoreanDict();
Lexicon engdict = new EnglishDict();
SpellChecker korchecker = new SpellChecker(kordict);
SpellChecker engchecker = new SpellChecker(engdict);
korcheker.isVaild("한국말");
engcheker.isVaild("English");
this.dictionary
로 받아서 사용했기 때문응용 : 생성자에 자원 팩토리를 넘겨주는 방식 (팩토리 메서드 패턴)
팩토리
= 호출될 때 마다 특정 타입의 인스턴스를 만들어주는 객체
Supplier<T> 인터페이스 = 팩토리의 완벽한 표현
~~String supplier= new String();
supplier = "Hello World";~~
Supplier<String> supplier= () -> "Hello World";
String result = supplier.get();
System.out.println(result); // Hello World