Movie
는 DiscountPolicy
추상 클래스에 의존DiscountPolicy
를 의존하고 있는 코드는 변경하지
않아도 된다.Movie
내부에서 AmounDiscountPolicy
를 생성public class Client {
public Movney getAvatarFee() {
Movie avatar = new Movie("아바타",
Duration.ofMinutes(120),
Money.wons(10000),
new AmountDiscountPolicy(...));
return avatar.getFee();
}
}
Client
로 옮긴 배경
Movie
가 특정 컨텍스트에 묶이지 않게 하기 위해Client
도 특정 컨텍스트에 묶이지 않기를 바란다면?Factory
라고 부른다.public class Factory {
public Movie createAvatarMovie() {
return new Movie("아바타",
Duration.ofMinutes(120),
Money.wons(10000),
new AmountDiscountPolicy(...));
}
}
public class Client {
private Factory factory;
public Cleint(Factory factory) {
this.factory = factory;
}
public Movney getAvatarFee() {
Movie avatar = factory.createAvatarMvoie();
return avatar.getFee();
}
}
FACTOR
로 객체 생성 책임을 이동시킴으로써 Client
는 사용과 관련된 책임만 남게 된다.FACTORY
도 도메인 모델이 아니다.public class Movie {
// ...
private DiscountPolicy discountPolicy;
public Movie(String title, Duration runningTime, Movie fee) {
this.title = title;
this.runningTime = runningTime;
this.fee = fee;
this.discountPolicy = ServiceLocator.discountPolicy();
}
}
Movie
의 퍼블릭 인터페이스에 DiscountPolicy
의존성이 나타나지 않는다.ServiceLocator
에서 DiscountPolicy
가 잘 들어가 있지 않다면 NPE를 마주할 수도 있다.ServiceLocator
는 내부적으로 정적 변수를 이용하기에 각 단위 테스트가 고립돼야 한다는 기본 원칙을 위반한다.Movie
가 사용되려면 ServiceLocator
에 구현체를 넣어두어야 함을 알아야 한다.Movie
/ DiscountPolicy
, AmountDiscountPolicy
, PercentDiscountPolicy
Movie
는 DiscountPolicy
를 의존하기에 정상적인 컴파일을 위해선 DiscountPolicy
가 필요DiscountPolicy
가 있는 패키지 안에 구체 클래스들도 포함되어 있다DiscountPolicy
가 포함된 패키지 안의 어떤 클래스가 수정되더라도 패키지 전체가 배포되어야 한다.Movie
, DiscountPolicy
/ AmountDiscountPolicy
, PercentDiscountPolicy
Movie
는 특정 컨텍스트로부터 완전 독립한다.