Effective Java 3/E
์์ดํ 5: ์์์ ์ง์ ๋ช ์ํ์ง ๋ง๊ณ ์์กด ๊ฐ์ฒด ์ฃผ์ ์ ์ฌ์ฉํ๋ผ
ํด๋์ค๋ค์ด ์์(๋ค๋ฅธ ํด๋์ค)์ ์์กดํ๋ ๊ฒฝ์ฐ๊ฐ ์๋ค.
์๋ฅผ ๋ค์ด์ SpellChecker๋ผ๋ ํด๋์ค์์ dictionary๋ผ๋ ์ ํธ๋ฆฌํฐ ํด๋์ค๋ฅผ ์ฌ์ฉํ๋ค๊ณ ๊ฐ์ ํด๋ณด๊ฒ ๋ค.
1. ์ ์ ์ ํธ๋ฆฌํฐ ํด๋์ค
public class SpellChecker {
private static final Lexicon dictionary = ...;
private SpellChecker() {} // ์ธ์คํด์คํ ๋ฐฉ์ง (์์ดํ
4 ์ฐธ๊ณ )
public static boolean isVaild(String word) {...}
public static List<String> suggestions(String typo) {...}
}
//์ฌ์ฉ์ ์ด๋ ๊ฒ!
SpellChecker.isValid(word);
2. ์ฑ๊ธํด
public class SpellChecker {
private final Lexicon dictionary = ...;
private SpellChecker() {} // ์ธ์คํด์คํ ๋ฐฉ์ง (์์ดํ
4 ์ฐธ๊ณ )
public static SpellChecker INSTANCE = new SpellChecker(...);
public static boolean isVaild(String word) {...}
public static List<String> suggestions(String typo) {...}
}
//์ฌ์ฉ์ ์ด๋ ๊ฒ!
SpellChecker.INSTANCE.isValid(word);
๋ ๋ฐฉ๋ฒ ๋ชจ๋ ํ์ฅ์ ์ ์ฐํ์ง ์๊ณ ํ ์คํธ๊ฐ ์ด๋ ต๋ค.
์ฌ์ ์ ๊ต์ฅํ ์ฌ๋ฌ ์ข
๋ฅ๊ฐ ์๋๋ฐ(ํ๊ตญ์ด ์ฌ์ , ์์ด ์ฌ์ , ํน์ ์ดํ์ฉ ์ฌ์ ๋ฑ...)
dictionary ํ๋๋ก๋ง ์ด ์ญํ ์ ๋ชจ๋ ์ํํ๊ธฐ์๋ ์ด๋ ต๊ณ ,
SpellChecker๋ dictionary ํ๋๋ง ์ฌ์ฉํ ์ ์๊ธฐ ๋๋ฌธ์ด๋ค.
์ฌ์ฉํ๋ ์์์ ๋ฐ๋ผ ๋์์ด ๋ฌ๋ผ์ง๋ ํด๋์ค๋ ์ ๋ ๋ฐฉ๋ฒ์ด ์ ํฉํ์ง ์๋ค.
๊ทธ๋ ๋ค๋ฉด ์๋์ ๊ฐ์ด final์ ์ญ์ ํ๊ณ ์ฌ์ ์ ๊ต์ฒดํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ๋ ๊ฒ์ ์ด๋จ๊น?
public class SpellChecker {
private static Lexicon dictionary = ...;
...
public static void changeDictionary(Lexicon newDictionary) {
dictionary = newDictionary;
}
...
}
//์ฌ์ฉ์ ์ด๋ ๊ฒ!
SpellChecker.changeDictionary(newDictionary);
-> ์ด์ํ๊ณ ๋ฉํฐ์ค๋ ๋ ํ๊ฒฝ์์๋ ์ฌ์ฉํ ์ ์๋ค.
3. ์์กด ๊ฐ์ฒด ์ฃผ์ ์ ํํ
์ด ๋ฐฉ๋ฒ์ ์ธ์คํด์ค๋ฅผ ์์ฑํ ๋ ์์ฑ์์๊ฒ ํ์ํ ์์์ ๋๊ฒจ์ฃผ๋ ๋ฐฉ์์ด๋ค.
์ฝ๋๋ฅผ ๋ณด๋๊ฒ ๋ ์ดํดํ๊ธฐ ํธํ๋ค.
public class SpellChecker {
private final Lexicon dictionary;
// ์ฌ๊ธฐ์ ์์กด์ฑ ์ฃผ์
์!
public SpellChecker(Lexicon dictionary){
this.dictionary = Objects.requireNotNull(dictionary);
}
public static boolean isVaild(String word) {...}
public static List<String> suggestions(String typo) {...}
}
// ์ธํฐํ์ด์ค
interface Lexicon {}
// Lexicon์ ์์ ๋ฐ์์ ๊ตฌํ
public class myDictionary implements Lexicon {
...
}
// ์ฌ์ฉ์ ์ด๋ ๊ฒ!
Lexicon dic = new myDictionary();
SpellChecker chk = new SpellChecker(dic);
chk.isVaild(word);
์ด ํจํด์ ์์ฉ ๋ฐฉ๋ฒ์ผ๋ก๋ ์์ฑ์์ ์์ ํฉํ ๋ฆฌ๋ฅผ ๋๊ฒจ์ฃผ๋ ๋ฐฉ์์ด ์๋ค. (ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด)
ex. Supplier
์ด์ฒ๋ผ ์์กด์ฑ ์ฃผ์ ์ ์ ์ฐ์ฑ๊ณผ ํ ์คํธ ์ฉ์ด์ฑ์ ๊ฐ์ ํด์ฃผ์ง๋ง, ์์กด์ฑ์ด ๋๋ฌด ๋ง์์ง๋ฉด ์ฝ๋๊ฐ ์ฅํฉํด์ง ์๋ ์๋ค.