tonykang22 / study

0 stars 0 forks source link

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

Open tonykang22 opened 2 years ago

tonykang22 commented 2 years ago

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


핵심 정리


예시 코드


Before

public class SpellChecker {

    private static final Dictionary dictionary = new DefaultDictionary();

    private SpellChecker() {}

    public static boolean isValid(String word) {
        // TODO 여기 SpellChecker 코드
        return dictionary.contains(word);
    }

    public static List<String> suggestions(String typo) {
        // TODO 여기 SpellChecker 코드
        return dictionary.closeWordsTo(typo);
    }
}


After

Dictionary가 interface라면 주입하는 방식으로 사용할 수 있다.

public class SpellChecker {

    private final Dictionary dictionary;

    public 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);
    }
}


class SpellCheckerTest {

    @Test
    void isValid() {
        SpellChecker spellChecker = new SpellChecker(new MockDictionaty());
        spellChecker.isValid("test");
    }

}



완벽 공략

예시 코드 (p.29)

... }


``` java
class SpellCheckerTest {

    @Test
    void isValid() {
        SpellChecker spellChecker = new SpellChecker(MockDictionary::new);
        spellChecker.isValid("test");
    }

}


스프링 IoC

BeanFactory 또는 ApplicationContext