SpellChecker
)가 사전(dictionary
)를 의존할 때 SpellChecker
를 정적 유틸 클래스나 싱글턴으로 사용하면 문제가 생긴다.// 정적 유틸 클래스를 잘못 사용한 예
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 final Lexicon dictionary = ...;
private SpellChecker() {}
public static SpellChecker INSTANCE = new SpellChecker(...);
public static boolean isValid(String word) { ... }
public static List<String> suggestions(String typo) { ... }
}
dictionary
필드에서 final
을 제거하고 다른 사전으로 교체하는 메서드(setter
)를 추가할 수도 있지만 오류를 내기 쉽고 멀티스레드 환경에서 쓸 수 없다.public class SpellChecker {
private final Lexicon dictionary;
public SpellChecker(Lexicon dictionary) {
this.dictionary = Objects.requireNonNull(dictionary);
}
public static boolean isValid(String word) { ... }
public static List<String> suggestions(String typo) { ... }
}