<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) { ... }
}

의존 객체 주입 방법

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");

응용 : 생성자에 자원 팩토리를 넘겨주는 방식 (팩토리 메서드 패턴)