이 글은 김영한 님의 스프링 핵심 원리 - 기본편(https://www.inflearn.com/스프링-핵심-원리-기본편/dashboard)을 수강하며 학습한 내용을 정리한 글입니다. 모든 출처는 해당 강의에 있습니다.
할인 정책을 기존의 고정 금액 할인에서 정률 할인으로 변경
[src/main/java/hello/core/discount/RateDiscountPolicy.java]
package hello.core.discount;
import hello.core.member.Grade;
import hello.core.member.Member;
public class RateDiscountPolicy implements DiscountPolicy {
private int discountPercent = 10; //10% 할인
@Override
public int discountMember(Member member, int price) {
if(member.getGrade() == Grade.VIP) //회원 등급이 VIP인 경우
return price * discountPercent / 100;
else
return 0;
}
}
[src/test/java/hello/core/discount/RateDiscountPolicyTest.java]
package hello.core.discount;
import hello.core.member.Grade;
import hello.core.member.Member;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.*;
class RateDiscountPolicyTest {
RateDiscountPolicy discountPolicy = new RateDiscountPolicy();
@Test
@DisplayName("VIP는 10% 할인이 적용되어야 한다")
void vip_o() {
//given
Member member = new Member(1L, "memberVIP", Grade.VIP);
//when
int discount = discountPolicy.discountMember(member, 10000);
//then
assertThat(discount).isEqualTo(1000);
}
@Test
@DisplayName("VIP가 아니면 할인이 적용되지 않아야 한다")
void vip_x() {
//given
Member member = new Member(2L, "memberBASIC", Grade.BASIC);
//when
int discount = discountPolicy.discountMember(member, 10000);
//then
assertThat(discount).isEqualTo(0);
}
}
OrderServiceImpl
코드 수정[src/main/java/hello/core/order/OrderServiceImpl.java]
public class OrderServiceImpl implements OrderService {
// private final DiscountPolicy discountPolicy = new FixDiscountPolicy();
private final DiscountPolicy discountPolicy = new RateDiscountPolicy();
}
항목 | 준수 여부 |
---|---|
역할과 구현을 충실하게 분리했는가? | O |
다형성을 활용했는가? | O |
인터페이스와 구현 객체를 분리했는가? | O |
객체지향 설계 원칙을 충실히 준수했는가? ex) OCP, DIP 등 | X |
DiscountPolicy
FixDiscountPolicy
, RateDiscountPolicy
FixDiscountPolicy
를RateDiscountPolicy
로 변경하는 순간OrderServiceImpl
의 소스 코드도 함께 변경해야 함 → OCP 위반
문제점
클라이언트 코드인 OrderServiceImpl
은 DiscountPolicy
의 인터페이스 뿐만 아니라 구체 클래스도 함께 의존
→ 구체 클래스 변경시 클라이언트 코드도 함께 변경해야 함
→ DIP 위반
해결 방법
추상(인터페이스)에만 의존하도록 의존관계를 변경
[src/main/java/hello/core/order/OrderServiceImpl.java]
public class OrderServiceImpl implements OrderService {
//private final DiscountPolicy discountPolicy = new RateDiscountPolicy();
private DiscountPolicy discountPolicy; //현재 값 → null
}
OrderServiceImpl
에 DiscountPolicy
의 구현 객체를 대신 생성 및 주입해 줄 존재 필요애플리케이션 전체 동작 방식을 구성(config)하기 위해, 구현 객체 생성 및 연결의 책임을 가지는 별도의 설정 클래스 생성
AppConfig
- 애플리케이션 전체 설정 및 구성[src/main/java/hello/core/AppConfig.java]
package hello.core;
import hello.core.discount.FixDiscountPolicy;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.member.MemoryMemberRepository;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
public class AppConfig {
public MemberService memberService() {
return new MemberServiceImpl(new MemoryMemberRepository());
}
public OrderService orderSerice() {
return new OrderServiceImpl(
new MemoryMemberRepository(),
new FixDiscountPolicy());
}
}
MemberServiceImpl
MemoryMemberRepository
OrderServiceImpl
FixDiscountPolicy
MemberServiceImpl
→ MemoryMemberRepository
OrderServiceImpl
→ MemoryMemberRepository
, FixDiscountPolicy
현재, 각 클래스에 생성자가 없는 상태이므로 컴파일 오류가 발생한다.
MemberServiceImpl
- 생성자 주입[src/main/java/hello/core/member/MemberServiceImpl.java]
package hello.core.member;
public class MemberServiceImpl implements MemberService {
private final MemberRepository memberRepository;
public MemberServiceImpl(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
public void join(Member member) {
memberRepository.save(member);
}
public Member findMember(Long memberId) {
return memberRepository.findById(memberId);
}
}
MemberServiceImpl
은 MemoryMemberRepository
를 의존 xMemoryMemberRepository
관련 코드가 전혀 존재 xMemberRepository
인터페이스만 의존 → DIP 충족AppConfig
)에 맡기고 실행에만 집중하면 됨Appconfig
)에서 결정AppConfig
: 객체의 생성 및 연결 담당MemberServiceImpl
은 구체 클래스를 알 필요 없이, 추상(MemberRepository
)에만 의존하면 됨AppConfig
MemberServiceImpl
memberServiceImpl
입장에서 보면 의존관계를 마치 외부에서 주입받고 있는 것처럼 보임
=> 의존성 주입(DI, Dependency Injection) = 의존관계 주입
OrderServiceImpl
- 생성자 주입[src/main/java/hello/core/order/OrderServiceImpl.java]
package hello.core.order;
import hello.core.discount.DiscountPolicy;
import hello.core.member.Member;
import hello.core.member.MemberRepository;
public class OrderServiceImpl implements OrderService {
private final MemberRepository memberRepository;
private final 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);
}
}
OrderServiceImpl
은 FixDiscountRepository
를 의존 xDiscountPolicy
인터페이스만 의존 → DIP 충족Appconfig
)에서 결정MemberApp
[src/main/java/hello/core/MemberApp.java]
package hello.core;
import hello.core.member.Grade;
import hello.core.member.Member;
import hello.core.member.MemberService;
public class MemberApp {
public static void main(String[] args) {
AppConfig appConfig = new AppConfig();
MemberService memberService = appConfig.memberService();
Member member = new Member(1L, "memberA", Grade.VIP);
memberService.join(member);
Member findMember = memberService.findMember(1L);
System.out.println("new member = " + member.getName());
System.out.println("find Member = " + findMember.getName());
}
}
OrderApp
[src/main/java/hello/core/OrderApp.java]
package hello.core;
import hello.core.member.Grade;
import hello.core.member.Member;
import hello.core.member.MemberService;
import hello.core.order.Order;
import hello.core.order.OrderService;
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);
}
}
[src/test/java/hello/core/member/MemberServiceTest.java]
class MemberServiceTest {
MemberService memberService;
@BeforeEach //테스트 실행하기 전 호출
public void beforeEach() {
AppConfig appConfig = new AppConfig();
memberService = appConfig.memberService();
}
}
[src/test/java/hello/core/order/OrderServiceTest.java]
class OrderServiceTest {
MemberService memberService;
OrderService orderService;
@BeforeEach
public void beforeEach() {
AppConfig appConfig = new AppConfig();
memberService = appConfig.memberService();
orderService = appConfig.orderService();
}
}
[src/main/java/hello/core/AppConfig.java]
package hello.core;
import hello.core.discount.FixDiscountPolicy;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.member.MemoryMemberRepository;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
public class AppConfig {
public MemberService memberService() {
return new MemberServiceImpl(new MemoryMemberRepository()); //중복
}
public OrderService orderService() {
return new OrderServiceImpl(
new MemoryMemberRepository(), //중복
new FixDiscountPolicy());
}
}
new MemoryMemberRepository()
중복[src/main/java/hello/core/AppConfig.java]
package hello.core;
import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepository;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
public class AppConfig {
public MemberService memberService() {
return new MemberServiceImpl(memberRepository());
}
public OrderService orderService() {
return new OrderServiceImpl(
memberRepository(),
discountPolicy());
}
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
public DiscountPolicy discountPolicy() {
return new FixDiscountPolicy();
}
}
new MemoryMemberRepository()
) 제거memberRepository()
만 변경하면 됨AppConfig
의 등장으로 애플리케이션이 크게 사용 영역과 구성(Configuration) 영역으로 분리됨
FixDiscountPolicy
에서 RateDiscountPolicy
로 변경하는 경우
[src/main/java/hello/core/AppConfig.java]
package hello.core;
import hello.core.discount.DiscountPolicy;
import hello.core.discount.FixDiscountPolicy;
import hello.core.discount.RateDiscountPolicy;
import hello.core.member.MemberService;
import hello.core.member.MemberServiceImpl;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepository;
import hello.core.order.OrderService;
import hello.core.order.OrderServiceImpl;
public class AppConfig {
public MemberService memberService() {
return new MemberServiceImpl(memberRepository());
}
public OrderService orderService() {
return new OrderServiceImpl(
memberRepository(),
discountPolicy());
}
public MemberRepository memberRepository() {
return new MemoryMemberRepository();
}
public DiscountPolicy discountPolicy() {
//return new FixDiscountPolicy();
return new RateDiscountPolicy();
}
}
FixDiscountPolicy
→ RateDiscountPolicy
AppConfig
만 변경하면 됨AppConfig
) → 변경 필요다형성 → 새로운 할인 정책 코드를 추가로 개발하는 것 자체는 문제 x
AppConfig
(공연 기획자) 등장AppConfig
의 등장으로 애플리케이션 영역 분리AppConfig
가 있는 구성 영역만 변경하면 됨