public class SpellChecker {
private static final Lexicon dictionary = new Lexicon();
private SpellChecker() {
}
public static boolean isValid(String word) {
}
public static List<String> suggestions(String typo) {
}
}
public class SpellChecker {
private final Lexicon dictionary = new Lexicon();
public static SpellChecker INSTANCE = new SpellChecker();
private SpellChecker() {
}
public static boolean isValid(String word) {
}
public static List<String> suggestions(String typo) {
}
}
//SpellChecker에 Dictionary를 주입해주면 Dictionary를 다양하게 쓸 수 있음 ex) Korean, English...
public class SpellChecker {
private final Dictionary dictionary;
private SpellChecker(Dictionary dictionary) {
this.dictionary = dictionary;
}
public boolean isValid(String word) {
// TODO 여기 SpellChecker 코드
return dictionary.contains(word);
}
public List<String> suggestions(String typo) {
// TODO 여기 SpellChecker 코드
return dictionary.closeWordsTo(typo);
}
}
// Dictionary가 바껴도 재사용성이 가능한 이유 -> interface
public interface Dictionary {
boolean contains(String word);
List<String> closeWordsTo(String typo);
}
테스트 코드를 사용할 때 유연해집니다.
class SpellCheckerTest {
@Test
void isValid() {
SpellChecker spellChecker = new SpellChecker(MockDictionary::new);
spellChecker.isValid("test");
}
}
// Dictionary를 상속받은 Mock 객체
public class MockDictionary implements Dictionary {
@Override
public boolean contains(String word) {
return false;
}
@Override
public List<String> closeWordsTo(String typo) {
return null;
}
}