회사 코드를 분석하다가 함수형인터페이스를 활용한 부분이 있어서 공부해보았다.
사용한 목적은 해당 EnumType 을 사용하면 그 Enum에 맞게 배열을 정렬했습니다.
신선한 충격을 받았습니다 ..ㅎ.. 그래서 저도 간단하게 구현해보고 공부해봤습니다!
package com.example.demo;
import java.util.function.Function;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
@Getter
@RequiredArgsConstructor
public enum ItemType {
AA("생수",CalRatio::getRatio),
BB("음료",CalRatio::getRatio),
CC("과자",CalRatio::getRatio);
final String type;
final Function<Long,Integer> ratio;
}
@RequiredArgsConstructor 을 사용해 final 이 선언된 필드들이 컴파일 시 아래와 같이 생성자로 생성됩니다
Long 파라미터 , Integer 리턴 한다.
ItemType(String type, Function<Long, Integer> ratio) {
this.type = type;
this.ratio = ratio;
}
생수에 대한 아이템의 가중치를 구해 코드에 포함 시켜야 한다면
(대충 만든 예제)
package com.example.demo;
public class CalRatio {
public static Integer getRatio(Long weight){
double totalWeight = 300;
return (int)Math.round(weight / totalWeight *100);
}
}
이런식으로 사용될 수 있습니다!
ItemType.AA.getRatio().apply(120L)
만약에 매개변수가 두 개인 경우에는 BiFunction 을 사용하면 됩니다!
Integer,Integer 파라미터를 받고 Integer로 Return 합니다!
final BiFunction<Integer,Integer,Integer> totalAccount;
public static Integer getTotalAccount(int quantity, int unit) {
return Math.round(quantity * unit);
}
ItemType.AA.totalAccount.apply(250,5)
간단하게 사용해본 경험을 공유해봅니다. 나중에 어떤식으로 제 프로젝트에 고도화 할지 설레이네요..........

'WEB > JAVA' 카테고리의 다른 글
나만 어려운 예외처리 (0) | 2022.05.19 |
---|---|
Test-Driven-Development 테스트 주도 개발 (0) | 2022.03.24 |
Java 8 Interface - default 메서드, static 메서드 (0) | 2022.03.23 |
[MapStruct] 내가 찾아 쓰려고 정리한 글 (0) | 2022.03.16 |
[Lombok] Difference Between @Value and @Data (0) | 2022.03.11 |