Item 5. Dependency Injection

์ž์›์„ ์ง์ ‘ ๋ช…์‹œํ•˜์ง€ ๋ง๊ณ  ์˜์กด ๊ฐ์ฒด ์ฃผ์ž…์„ ์‚ฌ์šฉํ•˜๋ผ

ํด๋ž˜์Šค๋ฅผ ์ž‘์„ฑํ•˜๋‹ค๋ณด๋ฉด ๋Œ€๋ถ€๋ถ„์˜ ํด๋ž˜์Šค๊ฐ€ ํ•˜๋‚˜ ์ด์ƒ์˜ ์ž์›์— ์˜์กดํ•˜๊ฒŒ ๋œ๋‹ค.

// 1. ์ •์  ์œ ํ‹ธ๋ฆฌํ‹ฐ ํด๋ž˜์Šค
class SpellChecker {
    private final Lexicon dictionary = new KoreanDictionary();

    private SpellChecker() {
    }

    // ...
}
// 2. ์‹ฑ๊ธ€ํ„ด
class SpellChecker {
    public static final SpellChecker INSTANCE = new SpellChecker();
    private final Lexicon dictionary = new KoreanDictionary();

    private SpellChecker() {
    }

    // ...
}

์ด๋Ÿฌํ•œ ํด๋ž˜์Šค๋ฅผ 1๋ฒˆ์ด๋‚˜ 2๋ฒˆ์ฒ˜๋Ÿผ ๊ตฌํ˜„ํ•˜๊ฒŒ ๋˜๋ฉด KoreanDictionary ํด๋ž˜์Šค์— ์˜์กดํ•˜๊ฒŒ ๋˜์–ด ์œ ์—ฐํ•˜๊ฒŒ ๋Œ€์ฒ˜ํ•  ์ˆ˜ ์—†๊ฒŒ ๋œ๋‹ค.

์˜์กด ๊ฐ์ฒด ์ฃผ์ž…

์ด๋Ÿฐ ๊ฒฝ์šฐ์—๋Š” ์˜์กด ๊ฐ์ฒด ์ฃผ์ž…์„ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•  ๋•Œ ์ƒ์„ฑ์ž์— ์˜์กด ๊ฐ์ฒด๋ฅผ ๋„˜๊ฒจ์ฃผ๋Š” ๋ฐฉ๋ฒ•๊ณผ ์ƒ์„ฑ์ž์— ์ง€์› ํŒฉํ„ฐ๋ฆฌ๋ฅผ ๋„˜๊ฒจ์ฃผ๋Š” ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.

// 3. ์ƒ์„ฑ์ž๋ฅผ ํ†ตํ•œ ์˜์กด ๊ฐ์ฒด ์ฃผ์ž…
class SpellChecker {
    private final Lexicon dictionary;

    public SpellChecker(Lexicon dictionary) {
        this.dictionary = Objects.requireNonNull(dictionary);
    }

    // ...
}
class SpellChecker {
    private final Lexicon dictionary;

    public SpellChecker(Supplier<? extends Lexicon> dictionary) {
        this.dictionary = Objects.requireNonNull(dictionary.get());
    }
}

๊ฒฐ๋ก ์ ์œผ๋กœ ํด๋ž˜์Šค์—์„œ ํ•˜๋‚˜ ์ด์ƒ์˜ ์ž์›์— ์˜์กดํ•˜๊ฒŒ ๋˜๋ฉด, 1,2๋ฒˆ ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ ๋ณด๋‹ค๋Š” 3,4 ๋ฒˆ์ฒ˜๋Ÿผ ์˜์กด ๊ฐ์ฒด ์ฃผ์ž…์„ ํ•˜๋Š” ๊ฒƒ์ด ์ข‹๋‹ค. ์ด ๋ฐฉ๋ฒ•์€ ๊ฒฐ๊ณผ์ ์œผ๋กœ ํด๋ž˜์Šค์˜ ์œ ์—ฐ์„ฑ/์žฌ์‚ฌ์šฉ์„ฑ/ํ…Œ์ŠคํŠธ ์šฉ์ด์„ฑ์„ ๋†’์—ฌ์ฃผ๊ฒŒ ๋œ๋‹ค.

Last updated