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
Was this helpful?