🌏 WEB/JAVA

Enum Type μ—μ„œ Function Interface ν™œμš©

μ• μ •μ“° 2022. 4. 1. 16:44

νšŒμ‚¬ μ½”λ“œλ₯Ό λΆ„μ„ν•˜λ‹€κ°€ ν•¨μˆ˜ν˜•μΈν„°νŽ˜μ΄μŠ€λ₯Ό ν™œμš©ν•œ 뢀뢄이 μžˆμ–΄μ„œ κ³΅λΆ€ν•΄λ³΄μ•˜λ‹€.

μ‚¬μš©ν•œ λͺ©μ μ€ ν•΄λ‹Ή 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)

 

κ°„λ‹¨ν•˜κ²Œ μ‚¬μš©ν•΄λ³Έ κ²½ν—˜μ„ κ³΅μœ ν•΄λ΄…λ‹ˆλ‹€. λ‚˜μ€‘μ— μ–΄λ–€μ‹μœΌλ‘œ 제 ν”„λ‘œμ νŠΈμ— 고도화 할지 μ„€λ ˆμ΄λ„€μš”..........

λ°˜μ‘ν˜•