사용하는 자원에 따라 동작이 달라지는 클래스에는 정적 유틸리티 클래스나 싱글턴 방식이 적합하지 않음 이 조건을 만족하는 간단한 패턴은 인스턴스를 생성할 때 생성자에 필요한 자원을 넘겨주는 방식
static 유틸리티를 잘못 사용한 예 - 유연하지 않고 테스트하기 어려움
public class SpellChecker {
private static final Lexicon dictionary = ...; // 의존하는 리소스 (의존성)
private SpellChecker() {} // 객체 생성 방지
public static boolean isValid(String word) { ... }
public static List<String> suggestions(String typo) { ... }
}
싱글턴을 잘못 사용한 예 - 유연하지 않고 테스트하기 어려움
public class SpellChecker {
private static final SpellChecker INSTANCE = new SpellChecker(new KoreanDictionary());
private final Lexicon dictionary;
private SpellChecker(Lexicon dictionary) {
this.dictionary = Objects.requireNonNull(dictionary);
}
public static SpellChecker getInstance() {
return INSTANCE;
}
public boolean isValid(String word) { return true; }
public List<String> suggestions(String typo) { return null; }
}
두 방식 모두 dictionary 를 단 하나만 사용한다고 가정할때 별로…
직접 명시 후 고정되어 있는 변수는 테스트를 하기 힘들게함
사용하는 자원에 따라 동작이 달라지는 클래스에는 정적 유틸리티 클래스나 싱글톤 방식이 적합하지 않음
의존 객체 주입은 유연성과 테스트 용이성을 높여줌!
public class SpellChecker {
private final Lexicon dictionary;
private SpellChecker(Lexicon dictionary) {
this.dictionary = Objects.requireNonNull(dictionary);
}
public boolean isValid(String word) { return true; }
public List<String> suggestions(String typo) { return null; }
public static void main(String[] args) {
Lexicon lexicon = new KoreanDictionary();
SpellChecker spellChecker = new SpellChecker(lexicon);
spellChecker.isValid("hello");
}
}
interface Lexicon{}
class KoreanDictionary implements Lexicon {}
class TestDictionary implements Lexicon {} // test가 가능해짐
불변을 보장하여 (변경될 일이 없음) 여러 클라이언트가 의존 객체들을 안심하고 공유할 수 있음
위의 예시에서는 단순히 한개의 자원만 사용하지만, 자원이 몇 개든 의존 관계가 어떻게 되든 잘 작동함!
Factory란?
Supplier<T>
인터페이스는 팩터리를 표현한 완벽한 예시@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
Mosaic create(Supplier<? extends Tile> tileFactory) { ... }
의존 객체 주입이 유연성과 테스트 용이성을 개선해주지만, 의존성이 너무 많은 프로젝트에서는 코드를 어지럽게 하며, 스프링 같은 의존 객체 주입 프레임워크를 사용해 코드의 어지러움을 해소할 수 있음!