결국, 역할은 있지만 그걸 구체적으로 누가 할지 선택하는 감독자 역할이 필요.
그 감독자가 컨테이너
public class MemberServiceImpl implements MemberService{
private final MemberRepository memberRepository;
public MemberServiceImpl(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
@Override
public void join(Member member) {
memberRepository.save(member);
}
@Override
public Member findMember(Long memberId) {
return memberRepository.findById(memberId);
}
}
기존처럼 구현체를 직접생성하지 말고, 오직 추상체만 의존한 뒤, 생성자를 통해 외부에서 주입.
잘 보면 아름답게도 모든 코드들이 추상체에만 의존하고 있음.
public class OrderServiceImpl implements OrderService{
private MemberRepository memberRepository;
private DiscountPolicy discountPolicy;
public OrderServiceImpl(MemberRepository memberRepository, DiscountPolicy discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
@Override
public Order createOrder(Long memberId, String itemName, int itemPrice) {
Member member = memberRepository.findById(memberId);
int discountPrice = discountPolicy.discount(member, itemPrice);
return new Order(memberId, itemName, itemPrice, discountPrice);
}
}
이것도
public class AppConfig {
public MemberService memberService(){
return new MemberServiceImpl(new MemoryMemberRepository());
}
public OrderService orderService(){
return new OrderServiceImpl(new MemoryMemberRepository(), new FixDscountPolicy());
}
}
주입해주는 역할, 역할을 관리해주는 역할.
정확히 역할만 의존하고, 실행하는 역할은 위가 해줌.
관심사의 분리.
public class MemberApp {
public static void main(String[] args) {
AppConfig appConfig = new AppConfig();
MemberService memberService = appConfig.memberService();
//MemberService memberService = new MemberServiceImpl();
Member member1 = new Member(1L, "kim", Grade.BASIC);
memberService.join(member1);
Member findMember = memberService.findMember(1L);
System.out.println("findMember = " + findMember.getName());
System.out.println("member1 = " + member1.getName());
}
}
appConfig를 통해 의존관계 주입.
public class OrderApp {
public static void main(String[] args) {
AppConfig appConfig = new AppConfig();
MemberService memberService = appConfig.memberService();
OrderService orderService = appConfig.orderService();
Long memberId = 1L;
Member member = new Member(memberId, "memberA", Grade.VIP);
memberService.join(member);
Order order = orderService.createOrder(memberId,"itemA", 10000);
System.out.println("order = " + order);
System.out.println("order.calculatePrice() = " + order.calculatePrice());
}
}
'스프링 > 1. 스프링 핵심 원리' 카테고리의 다른 글
16강. Rate할인으로 변경 (0) | 2023.07.16 |
---|---|
15강. AppConfig 리팩토링 (0) | 2023.07.16 |
13강. 퍼센트 할인정책 추가의 문제점. (0) | 2023.07.16 |
12강. 퍼센트 할인정책 구현 + 테스트 (0) | 2023.07.16 |
11강. 주문할인정책 테스트 (0) | 2023.07.16 |