맞춤법을 검사 할 때, 필요에 따라 다른 종류의 사전이 필요한 class는 아래와 같이 instance를 생성할 때 생성자에 필요한 자원을 넘겨준다.
public class SpellChecker {
private final Lexicon dictionary;
public SpellChecker(Lexicon dictionary) {
this.dictionary = dictionary;
}
...
}
이유는 위 코드에서 볼 수 있다.
의존 객체 주입이 되는 field는 final 한정자를 가지고 있기 때문에 한번 주입되면 값을 바꿀 수 없다.
아래의 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) { ... }