[모던 자바 인 액션] - 2장 동작 파라미터화 코드 전달하기

태히·2024년 4월 17일
0

동작파라미터화

  • 동작 파라미터화란 아직은 어떻게 실행할 것인지 결정하지 않은 코드 블록을 의미한다.
  • 자주 바뀌는 요구사항에 대해 유연하게 대응할 수 있음
    - 사과의 색 / 무게 등을 필터링 할 때
    - 두가지 모두 필터링 할때.
  • 유연하게 대응하기 위해서 interface를 사용한다.
    public List<Apple> filterApples(List<Apple> inventory, Color color, int weight, boolean flag) {
        //두가지 필터링이 존재
        List<Apple> result = new ArrayList<>();
        for (Apple apple : inventory) {
            if ((flag && apple.getColor().equals(color)) ||
                    !flag && apple.getWeight() > weight) {
                result.add(apple);
            }
        }
        return result;
    }
        public void 모든_속성으로_필터링() {
            //초록 사과만 필터링
            List<Apple> greenApples = filterApples(inventory, Color.GREEN, 0, true);
            //무게 150이상만 필터링
            List<Apple> heavyApples = filterApples(inventory, null, 150, false);
        }
    • 위 같이 무게 또는 색으로 하나만 필터링 하고 싶지만, 파라미터에는 모두 넣어줘야 한다.
  • Predicate : 참 또는 거짓을 반환하는 함수
public interface ApplePredicate {
    boolean test (Apple apple);
}

public class AppleHeavyWeightPredicate implements ApplePredicate{
    @Override
    public boolean test(Apple apple) {
        return apple.getWeight() > 150;
    }
}
public class AppleGreenColorPredicate implements ApplePredicate{
    @Override
    public boolean test(Apple apple) {
        return Color.GREEN.equals(apple.getColor());
    }
}
  • 위 predicate 함수를 사용해서 유연하게 필터링을 만들 수 있다.
  • 3장에서 계속,,,
  • 동작 파라미터화 방법
    • 클래스
    • 익명 클래스
    • 람다
profile
하고싶은게 많은 개발자가 되고싶은

0개의 댓글