Service 활용법
- 동일한
Interface를 사용할 때, 어떤 클래스의 인스턴스를 생성할지 팩토리 클래스가 결정하도록 하는 패턴
Note
이 글은 Payment를 예시로 진행한다.
-
Interface
javapublic interface IPaymentService { void process(int amount); String getType(); } @Service public class CardPaymentService implements IPaymentService { public void process(int amount) { /* 카드 결제 로직 */ } public String getType() { return "CARD"; } } @Service public class NaverPaymentService implements IPaymentService { public void process(int amount) { /* 네이버페이 로직 */ } public String getType() { return "NAVER"; } } @Service public class BankingPaymentService implements IPaymentService { public void process(int amount) { /* 계좌이체 로직 */ } public String getType() { return "BANKING"; } } -
PaymentFactory.java
java@Component public class PaymentFactory { private final Map<String, IPaymentService> paymentServices; // Spring이 모든 PaymentService 구현체를 Map으로 주입해줍니다. // Key는 Bean 이름이나 별도 정의한 타입으로 설정 가능합니다. public PaymentFactory(List<IPaymentService> services) { // 주입받은 Serivces를 이용하기 쉽게 type별로 Map 저장 this.paymentServices = services.stream() .collect(Collectors.toMap(PaymentService::getType, Function.identity())); } public PaymentService getPaymentService(String type) { PaymentService service = paymentServices.get(type.toUpperCase()); if (service == null) { throw new IllegalArgumentException("지원하지 않는 결제 수단입니다."); } return service; } }
Tip
의존성 주입을 위해 생성자를 만들 때, 매개변수로 Interface List를 넣게 되면, Interface가 implements 된 클래스를 Bean으로 등록한다.
Static Factory Method
- 클래스의 인스턴스를 생성할 때
new키워드 대신, 클랫스 내부에public static메소드를 만들어 객체 생성을 위임하는 방식
from
- 매개변수를 하나 받아서 해당 타입의 인스턴스를 반환할 때
Date date = Date.from(instant);
of
- 여러 매개변수를 받아 적절한 인스턴스를 반환할 때
List<String> list = List.of("A", "B", "C");
valueOf
- from이나 of와 비슷하지만 더 세밀하게 값을 표현할 때
Integer i = Integer.valueOf("123");