본문 바로가기

Dev Book Review/Effective Java

[Effective Java] item5. 자원을 직접 명시하지 말고 의존 객체 주입을 사용하라

사용하는 자원에 따라 동작이 달라지는 클래스에는 정적 유틸리티 클래스나 싱글턴 방식이 적합하지 않다.

  • 인스턴스를 생성할 때 생성자에 필요한 자원을 넘겨주는 방식을 사용하자
  • 의존 객체 주입의 형태!!
// 정적 유틸리티 클래스 X
public class SpellChecker{
  private static final Lexicon dictionary = ...;
  private SpellChecker(){} // 객체 생성 방지
}

// 싱글턴 X
public class SpellChecker{
  private final Lexicon dictionary = ...;
  private SpellChecker(...){}
  public static SpellChecker INSTANCE = new SPellChecker(...);
}

// 의존 객체 주입 형태 O
public class SpellChecker{
  private final Lexicon dictionary;
  
  public SpellChecker(Lexicon dictionary){
    this.dictionary = Objects.requireNonNull(dictionary);
  }
  
  public boolean isValid(String word){...}
  public List<String> suggestions(String typo){...}
}

스펠 체커가 여러 사전을 사용할 수 있다고 할 때, 싱글턴이나 정적 유틸리티 클래스에서 새로운 사전으로 교체하는 메서드를 추가하기보단, 의존 객체 주입 형태가 올바르다.

  • 불변을 보장한다.
  • 생성자, 정적 팩터리, 빌더 모두에 똑같이 응용할 수 있다.

 

생성자에 자원팩터리를 넘겨주는 방식

팩터리 = 호출할 때마다 특정 타입의 인스턴스를 반복해서 만들어주는 객체 (팩터리 메서드 패턴)

Supplier<T> 인터페이스: 팩터리를 표현함
한정적 와일드 카드 타입 (bounded wildcard type)으로 팩터리 타입 매개변수를 제한한다. (ITypeFactory.class)

IType의 하위타입이어도 map에 put이 가능하다. (리스코프의 치환원칙에 적용 되는 듯)

public class IType {
    private static final int TYPE_Z = 0;
    private static final int TYPE_A = 1;
    private static final int TYPE_B = 2;

    final static Map<Integer, Supplier<? extends ITypeFactory>> map = new HashMap<>();
    static {
	map.put(TYPE_Z, ITypeFactory::new);
        map.put(TYPE_A, A::new);
        map.put(TYPE_B, B::new);
    }
}

class ITypeFactory {}
class A extends ITypeFactory {}
class B extends ITypeFactory {}

 

의존객체 주입 프레임 워크

대거(Dagger), 주스(Guice), 스프링(Spring)
의존객체를 직접 주입하도록 설계된 API를 알맞게 응용해 사용하고 있다.