ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바의 Supplier와 Consumer 인터페이스 이해와 활용
    Tech/SpringBoot 2023. 10. 9. 13:49
    반응형

    자바의 Supplier와 Consumer 인터페이스는 자바 8에서 소개된 함수형 인터페이스로, 각각 데이터를 제공하는 로직과 데이터를 소비하는 로직을 간단하게 표현하는데 사용됩니다.

    Supplier 인터페이스

    Supplier<T> 인터페이스는 파라미터를 받지 않고 값을 리턴하는 get() 메소드를 가지고 있습니다.

    @FunctionalInterface
    public interface Supplier<T> {
        T get();
    }

    Consumer 인터페이스

    반면 Consumer<T> 인터페이스는 파라미터를 하나 받아서 소비하고 (처리하고) 리턴 값이 없는 accept() 메소드를 가지고 있습니다

    @FunctionalInterface
    public interface Consumer<T> {
        void accept(T t);
    }

    예제: 온라인 쇼핑몰 결제 로직 처리

    1. 결제 정보 및 요청 DTO 정의

    public class PaymentRequest {
        private String userId;
        private double amount;
        // ... getters and setters ...
    }
    
    public class PaymentResponse {
        private String status;
        private String transactionId;
        // ... getters and setters ...
    }

    2. Supplier 및 Consumer 활용한 서비스 클래스 정의

    @Service
    public class PaymentService {
    
        private final Map<String, Supplier<Consumer<PaymentRequest>>> paymentStrategies;
    
        public PaymentService() {
            this.paymentStrategies = new HashMap<>();
            paymentStrategies.put("credit", () -> this::handleCreditPayment);
            paymentStrategies.put("paypal", () -> this::handlePayPalPayment);
        }
    
        public void pay(String method, PaymentRequest request) {
            Consumer<PaymentRequest> paymentStrategy = 
            Optional.ofNullable(paymentStrategies.get(method))
               .orElseThrow(() 
               -> new IllegalArgumentException("Invalid payment method: " + method))
               .get();
            paymentStrategy.accept(request);
        }
    
        private void handleCreditPayment(PaymentRequest request) {
            // handle credit card payment...
            System.out.println("Credit payment: " + request.getAmount());
        }
    
        private void handlePayPalPayment(PaymentRequest request) {
            // handle PayPal payment...
            System.out.println("PayPal payment: " + request.getAmount());
        }
    }

    여기서, Supplier<Consumer<PaymentRequest>> 형태를 사용하여 지연 로딩(lazy loading) 전략을 적용하였습니다. 즉, 결제 방법에 따른 로직은 실제로 호출되는 시점에 생성되고 처리됩니다.

    3. 컨트롤러 클래스 정의

    @RestController
    @RequestMapping("/api/payment")
    public class PaymentController {
        
        @Autowired
        private PaymentService paymentService;
        
        @PostMapping("/{method}")
        public ResponseEntity<String> pay(@PathVariable String method, 
        @RequestBody PaymentRequest request) {
            paymentService.pay(method, request);
            return ResponseEntity.ok("Payment successful!");
        }
    }

    정리

    이 예제에서는 Supplier 인터페이스를 활용하여 결제 처리 로직 (Consumer)을 제공하고, Consumer를 활용하여 받은 PaymentRequest를 처리하는 방법을 보여줍니다. 이러한 방식은 결제 처리 로직이 상황에 따라 동적으로 결정되어야 할 때 유용하게 사용될 수 있습니다.

     

    반응형
Designed by Tistory.