본문 바로가기
공부/이펙티브자바

[이펙티브자바]item5.자원을 직접 명시하지 말고 의존 객체 주입을 사용하라.

by 띵커베르 2023. 1. 13.
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

댓글