item 5 lsucret - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki
μ μ μ νΈλ¦¬ν°λ μ±κΈν΄ ν¨ν΄μ μ¬μ©ν΄ μ½λλ₯Ό μ§κ² λλ©΄ ν΄λΉ κ°μ²΄λ μ€μ§ ν μ’ λ₯μ μΈμ€ν΄μ€λ§ μμ±ν μ μλ€.
//μ μ μ νΈλ¦¬ν°
public class SpellChecker {
private static final Lexicon dictionary = new Lexicon("english"); // μ¬μ μ΄ νλλΏμ΄λ€.
private SpellChecker() {} // κ°μ²΄ μμ± λ°©μ§
public static boolean isValid(String word) {...}
public static List<String> suggestions(String typo) {...}
}
public class Main {
public static void main(String[] args) {
SpellChecker.isValid("hypopotamus");
}
}
//μ±κΈν΄
public class SpellChecker {
private final Lexicon dictionary = new Lexicon(); // μ¬μ μ΄ νλλΏμ΄λ€
private SpellChecker() {} // κ°μ²΄ μμ± λ°©μ§
public static SpellChecker INSTANCE = new SpellChecker();
public boolean isValid(String word) {}
public List<String> suggestions(String type) {}
}
public class Main {
public static void main(String[] args) {
SpellChecker.INSTANCE.isValid("Hippopotamus");
}
}
- μ¬μ νλλ§ κ°μ§κ³ μ¬λ¬ μν©μ λμνλ κ²μ νμ€μ μΌλ‘ λΆκ°λ₯
- λ§μ½ μμ΄ μ¬μ λ§κ³ μ€κ΅μ΄ μ¬μ μ΄ νμνλ€λ©΄? μμ΄ μ€ νΉμ μ©μ΄ μ¬μ μ΄ νμνλ€λ©΄? ν μ€νΈμ© μ¬μ μ΄ νμνλ€λ©΄?
- μ¬λ¬ μ¬μ μ μ¬μ©ν μ μλλ‘ μ½λ μμ μ΄ νμ
λμ 1. νλμμ finalμ μ κ±°νκ³ setter λ©μλλ₯Ό μ¬μ©ν΄ λ€λ₯Έ μ¬μ μΌλ‘ κ΅μ²΄νλ€
- μ€λ₯κ° λ°μνκΈ° μ½κ³ , (code, data heap μμμ 곡μ νλ) λ©ν°μ€λ λ νκ²½μμ μ¬μ©λΆκ°
// μμ‘΄ κ°μ²΄ μ£Όμ
ν¨ν΄
public class SpellChecker {
private final Lexicon dictionary;
public SpellChecker(Lexicon dictionary) {
this.dictionary = Objects.requireNonNull(dictionary);
}
public boolean isValid(String word) { return false;}
public List<String> suggestions(String typo) { return null;}
}
- dictionaryλΌλ μμ νλλ₯Ό μ¬μ©νλ°λ€, μΈλΆμμ μ΄λ€ μμ‘΄μ±μ μ£Όμ νλμ§ μκ΄μμ΄ μ λμνλ€.
- finalλ‘ λΆλ³μ 보μ₯νμ¬ μ¬λ¬ ν΄λΌμ΄μΈνΈκ° μμ‘΄ κ°μ²΄λ€μ μμ¬νκ³ κ³΅μ ν μ μλ€.
μ μ¬ν λ°©μμΌλ‘ ν©ν°λ¦¬ λ©μλ ν¨ν΄μ΄ μλ€.
Mosaic create(Supplier<? extends Tile> tileFactory) { ... }
- ν΄λΌμ΄μΈνΈκ° μ 곡ν ν©ν°λ¦¬κ° μμ±ν νμΌλ€λ‘ ꡬμ±λ λͺ¨μμ΄ν¬λ₯Ό λ§λλ λ©μλ
- μμ μ΄ λͺ μν νμ μ νμ νμ μ΄λ©΄ 무μμ΄λ μμ±ν μ μλ ν©ν°λ¦¬λ₯Ό λκΈ΄λ€.
- μΈν°νμ΄μ€ Supplierκ° ν©ν°λ¦¬λ₯Ό ꡬνν μλ²½ν μλ‘, Supplierλ₯Ό μ λ ₯μΌλ‘ λ°λ λ©μλλ μΌλ°μ μΌλ‘ νμ μ μμΌλμΉ΄λ νμ (bounded wildcard type)μ μ¬μ©ν΄ ν©ν°λ¦¬μ νμ 맀κ°λ³μλ₯Ό μ ννλ€.
- μμ‘΄κ°μ²΄μ£Όμ μ μ¬μ©νλ©΄ μ μ°μ±κ³Ό ν μ€νΈ μ©μ΄μ±μ κ°μ ν΄μ£Όμ§λ§, μμ‘΄μ± μ£Όμ μ μκ° λ μλ‘ μ½λκ° μ΄μ§λ¬μμ§λ€.
- λκ±°(Dagger), μ£Όμ€(Guice), μ€νλ§(Spring) κ°μ μμ‘΄ κ°μ²΄ μ£Όμ μ λμ ν΄μ£Όλ νλ μμν¬λ₯Ό μ¬μ©νλ©΄ μ΄λ° μ΄μ§λ¬μμ ν΄μν μ μλ€.
ν΄λμ€κ° λ΄λΆμ μΌλ‘ νλ μ΄μμ μμμ μμ‘΄νκ³ κ·Έ μμμ΄ ν΄λμ€ λμμ μν₯μ μ€λ€λ©΄ μμ‘΄ κ°μ²΄ μ£Όμ μ μ¬μ©νλΌ. μμ‘΄ κ°μ²΄ μ£Όμ μ λ³κ²½μ΄ νμμλ λΆλΆμ κ·Έλλ‘ λλ, λ³κ²½μ΄ νμν μμμ μμ±μλ₯Ό ν΅ν΄ μΈλΆμμ μ£Όμ λ°μ μ¬μ©νμ. μ΄ λ°©λ²μ ν΄λμ€μ μ μ°μ±, μ¬μ¬μ©μ±, ν μ€νΈ μ©μ΄μ±μ κ°μ ν΄μ€λ€.