이펙티브 자바 아이템5 용어 정리

이창호·2022년 4월 13일
0

이펙티브자바

목록 보기
7/12

의존 객체 주입

맞춤법을 검사 할 때, 필요에 따라 다른 종류의 사전이 필요한 class는 아래와 같이 instance를 생성할 때 생성자에 필요한 자원을 넘겨준다.

public class SpellChecker {
	private final Lexicon dictionary;
    
    public SpellChecker(Lexicon dictionary) {
    	this.dictionary = dictionary;
    }
    ...
}

의존 객체 주입은 불변을 보장한다.

이유는 위 코드에서 볼 수 있다.
의존 객체 주입이 되는 field는 final 한정자를 가지고 있기 때문에 한번 주입되면 값을 바꿀 수 없다.

static factory, builder에도 의존 객체 주입을 사용 할 수 있다.

아래의 class는 FactoryTemplate는 생성자를 통해 어떤 인스턴스를 만들지 결정된다.

public interface Facotry{ ... }

public class Factory {
    private static Factory factory;
        
    private FactoryTemplate(Factory factory){ 
        ...
	}
        
	public static FactoryTemplate create(Factory factory) {
        ...
	}
}

마찬가지로 Builder Pattern으로 객체를 생성해도 똑같이 할 수 있다.

public class Car {
	private final Engine engine;
    private final Wheel wheel;
    
    public static class Builder {
    	private final Engine engine;
        private final Wheel wheel;
        
        public Builder(Engine engine, Wheel wheel) {
        	this.engine = engine;
            this.wheel = wheel;
        }
        
        public Builder engine(Engine engine){
        	this.engine = engine;
            return this;
        }
        
        public Builder wheel(Wheel wheel){
        	this.wheel = wheel;
            return this;
        }
    }
    
    public Car(Builder builder) {
    	this.engine = builder.engine;
		this.wheel = builder.wheel;
    }
}

한정적 와일드카드

아래 메서드는 tileFactory가 제공하는 Tile로 Mosaic를 만든다.

	Mosaic create(Supplier<? extends Tile> tileFactory) { ... }
profile
이타적인 기회주의자

0개의 댓글