ํ์ฌ ์ฝ๋๋ฅผ ๋ถ์ํ๋ค๊ฐ ํจ์ํ์ธํฐํ์ด์ค๋ฅผ ํ์ฉํ ๋ถ๋ถ์ด ์์ด์ ๊ณต๋ถํด๋ณด์๋ค.
์ฌ์ฉํ ๋ชฉ์ ์ ํด๋น 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' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ฉด์ ์ํ๋ ์๋ฌ๋ฉ์์ง ๋ณด๋ด๊ธฐ (1) | 2023.03.09 |
---|---|
๋๋ง ์ด๋ ค์ด ์์ธ์ฒ๋ฆฌ (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 |