아이템 5. 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라

hany·2022년 12월 2일
0

effective-java

목록 보기
4/4
  • 사용하는 자원에 따라 동작이 달라지는 클래스는 적합하지 않는 방식 ex) 사전 - 국어사전, 영어사전
    • 정적 유틸리티 클래스
    • 싱글턴 방식
  • 의존 객체 주입:
    • 정의: 인스턴스를 생성할 때 필요한 자원을 넘겨주는 방식
    • 결과: 생성자에 자원 팩터리를 넘겨줌
    • 장점: 클래스의 유연성, 재사용성, 테스트 용이성 개선

정적 유틸리티 클래스를 사용한 방식

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;
    }
}
profile
number1hany

0개의 댓글

관련 채용 정보