728x90
- 하나의 클래스에서 여러 리소스를 사용하려면 아래와 같은 코드는 KoreanDicationary 만 사용할 수 있게 코드가 박혀있으니,
public class SpellChecker {
private Lexicon dictionary;
public SpellChecker(Lexicon dictionary) {
this.dictionary = dictionary;
}
private SpellChecker(){}
public boolean isValid(String word) {
return true;
}
public List<String> suggestions(String typo) {
throw new UnsupportedOperationException();
}
public static void main(String[] args) {
Lexicon lexicon = new EngDictionary();
SpellChecker spellChecker = new SpellChecker(lexicon);
spellChecker.isValid("java");
}
}
interface Lexicon {}
class KoreanDictionary implements Lexicon {}
class EngDictionary implements Lexicon {}
위 코드를 아래처럼 써라는것, 생성자를 받아서 사용하면 될 듯 하다.
public class SpellChecker {
private static final Lexicon dictionary = new KoreanDictionary();
private SpellChecker(){}
public static boolean isValid(String word) {
return true;
}
public List<String> suggestions(String typo) {
throw new UnsupportedOperationException();
}
public static void main(String[] args) {
SpellChecker.isValid("hello");
}
}
interface Lexicon {}
class KoreanDictionary implements Lexicon {}
이렇게 받아도 되고, 팩토리 패턴을 써도 될듯.
*팩토리 패턴:
- 객체를 생성할 때 필요한 인터페이스를 만듭니다.
- 어떤 클래스의 인스턴스를 만들지는 서브클래스에서 결정합니다.
- 팩토리 메소드 패턴을 사용하면 클래스 인스턴스 만드는 일을 서브클래에게 맡기게 됩니다.
728x90
'공부 > 이펙티브자바' 카테고리의 다른 글
[이펙티브자바]item7.다 쓴 객체 참조를 해제하라. (0) | 2023.01.13 |
---|---|
[이펙티브자바]item6.불필요한 객체 생성을 피하라 (0) | 2023.01.13 |
[이펙티브 자바]item4.인스턴스를 막으려거든 private 생성자를 사용하라. (0) | 2023.01.13 |
[이펙티브 자바]item3.private 생성자나 열거 타입으로 싱글턴임을 보장하라 (0) | 2023.01.11 |
[이펙티브 자바]item2.생성자에 매개변수가 많다면 빌더를 고려하라 (0) | 2023.01.11 |
댓글