item 5 leekyunghee - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki

μžμ›μ„ 직접 λͺ…μ‹œν•˜μ§€ 말고 의쑴 객체 μ£Όμž…μ„ μ‚¬μš©ν•˜λΌ

  • μΈμŠ€ν„΄μŠ€λ₯Ό 생성할 λ•Œ μƒμ„±μžμ— ν•„μš”ν•œ μžμ›μ„ λ„˜κ²¨μ£ΌλŠ” 방식이닀.
  • 의쑴 객체 μ£Όμž…μ˜ ν•œ ν˜•νƒœλ‘œ λ§žμΆ€λ²• 검사기(μ˜ˆμ‹œ)λ₯Ό 생성할 λ•Œ 객체인 사전을 μ£Όμž…ν•΄μ£Όλ©΄ λœλ‹€.

의쑴 객체 μ£Όμž… νŒ¨ν„΄

public class SpellChecker {
    private final Lexicon dictionary;
    public SpellChecker(Lexicon dictionary) {
        this.dictionary = Objects.requireNonNull(dictionary);
    }
    public boolean isValid(String word) { ... }
    public List<String> suggestings (String typo) { ... } 
}

μ˜ˆμ‹œμ—μ„œλŠ” dictionaryλΌλŠ” λ”± ν•˜λ‚˜μ˜ μžμ›λ§Œ μ‚¬μš©ν•˜μ§€λ§Œ μžμ›μ΄ λͺ‡κ°œλ“  의쑴 관계가 μ–΄λ–»λ“  상관없이 잘 μž‘λ™ν•œλ‹€.

λΆˆλ³€(μ•„μ΄ν…œ17)을 보μž₯ν•˜μ—¬ (같은 μžμ›μ„ μ‚¬μš©ν•˜λ €λŠ”) μ—¬λŸ¬ ν΄λΌμ΄μ–ΈνŠΈκ°€ 의쑴 객체듀을 μ•ˆμ‹¬ν•˜κ³  κ³΅μœ ν•  수 μžˆκΈ°λ„ ν•œλ‹€.

  • 의쑴 객체 μ£Όμž…μ€ μƒμ„±μž, 정적 νŒ©ν† λ¦¬, λΉŒλ” λͺ¨λ‘μ— λ˜‘κ°™μ΄ μ‘μš©ν•  수 μžˆλ‹€.

νŒ©ν† λ¦¬ λ©”μ„œλ“œ νŒ¨ν„΄

  • μƒμ„±μžμ— μžμ› νŒ©ν† λ¦¬λ₯Ό λ„˜κ²¨μ£ΌλŠ” 방식
  • νŒ©ν† λ¦¬λž€ ν˜ΈμΆœν•  λ•Œλ§ˆλ‹€ νŠΉμ • νƒ€μž…μ˜ μΈμŠ€ν„΄μŠ€λ₯Ό λ°˜λ³΅ν•΄μ„œ λ§Œλ“€μ–΄μ£ΌλŠ” 객체 λ₯Ό λ§ν•œλ‹€.
  • μžλ°” 8μ—μ„œ μ†Œκ°œν•œ Supplier<T> μΈν„°νŽ˜μ΄μŠ€κ°€ νŒ©ν† λ¦¬λ₯Ό ν‘œν˜„ν•œ μ™„λ²½ν•œ μ˜ˆμ‹œμ΄λ‹€.

잘λͺ» μ‚¬μš©ν•œ μ˜ˆμ‹œ - μœ μ—°ν•˜μ§€ μ•Šκ³  ν…ŒμŠ€νŠΈν•˜κΈ° μ–΄λ ΅λ‹€.

정적 μœ ν‹Έλ¦¬ν‹°λ₯Ό 잘λͺ» μ‚¬μš©ν•œ 예

public class SpellChecker {
    private static final Lexicon dictionary = ...;
    
    private SpellChecker() {}  // 객체 생성 방지 
    public static boolean isValid(String word) { ... }
    public static List<String> suggestings (String typo) { ... } 
}

싱글턴을 잘λͺ» μ‚¬μš©ν•œ 예

public class SpellChecker {
    private final Lexicon dictionary = ...;
    
    private SpellChecker(...) {}  
    private static SpellChecker INSTANCE = new SpellChecker(...); 
    public boolean isValid(String word) { ... } 
    public List<String> suggetions(String type)  { ... } 
}
  • dictionaryλ₯Ό 단 ν•˜λ‚˜λ§Œ μ‚¬μš©ν•œλ‹€κ³  κ°€μ •ν•œλ‹€λŠ” 점
  • 사전 ν•˜λ‚˜λ‘œ 이 λͺ¨λ“  μ“°μž„μ— λŒ€μ‘ν•  수 있게 ν•œλ‹€λŠ” 점
  • μ‚¬μš©ν•˜λŠ” μžμ›μ— 따라 λ™μž‘μ΄ λ‹¬λΌμ§€λŠ” ν΄λž˜μŠ€μ—λŠ” 정적 μœ ν‹Έλ¦¬ν‹° ν΄λž˜μŠ€λ‚˜ μ‹±κΈ€ν„΄ 방식이 μ ν•©ν•˜μ§€ μ•Šλ‹€.

핡심 정리

ν΄λž˜μŠ€κ°€ λ‚΄λΆ€μ μœΌλ‘œ ν•˜λ‚˜ μ΄μƒμ˜ μžμ›μ— μ˜μ‘΄ν•˜κ³ , κ·Έ μžμ›μ΄ 클래슀 λ™μž‘μ— 영ν–₯을 μ€€λ‹€λ©΄ 
μ‹±κΈ€ν„΄κ³Ό 정적 μœ ν‹Έλ¦¬ν‹° ν΄λž˜μŠ€λŠ” μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”κ²Œ μ’‹λ‹€. 이 μžμ›μ„ ν΄λž˜μŠ€κ°€ 직접 λ§Œλ“€κ²Œ ν•΄μ„œλ„ μ•ˆλœλ‹€. 

ν•„μš”ν•œ μžμ›μ„ (ν˜Ήμ€ κ·Έ μžμ›μ„ λ§Œλ“€μ–΄μ£ΌλŠ” νŒ©ν† λ¦¬λ₯Ό) μƒμ„±μžμ— (ν˜Ήμ€ 정적 νŒ©ν† λ¦¬λ‚˜ λΉŒλ”μ—) λ„˜κ²¨μ£Όμž.

⚠️ **GitHub.com Fallback** ⚠️