Modern Java in Action - Ch.2

참고: 책 - Modern Java in Action

Ch 2. 동작 파라미터화 코드 전달하기

변화하는 요구사항에 대응하기

package com.programmers.java.modern.ch2;

public class Apple {
    private Color color;
    private int weight;

    public Apple(Color color) {
        this.color = color;
    }

    public Color getColor() {
        return color;
    }

    public int getWeight() {
        return weight;
    }
}
package com.programmers.java.modern.ch2;

public enum Color {
    RED, GREEN;
}

디자인 패턴 활용

image

public interface ApplePredicate {
    boolean test(Apple apple);
}
public class AppleGreenColorPredicate implements ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return GREEN.equals(apple.getColor());
    }
}
public class AppleHeavyWeightPredicate implements ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return apple.getWeight() > 150;
    }
}
public class AppleRedAndHeavyPredicate implements ApplePredicate {
    @Override
    public boolean test(Apple apple) {
        return RED.equals(apple.getColor()) && apple.getWeight() > 150;
    }
}
public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate predicate) {
    List<Apple> result = new ArrayList<>();
    for (Apple apple : inventory) {
        if (predicate.test(apple)) {
            result.add(apple);
        }
    }
    return result;
}

익명 클래스

참고 - 익명클래스의 장황함

public class MeaningOfThis {
    public final int value = 4;
    public void doIt() {
        int value = 6;
        Runnable r = new Runnable() {
            public final int value = 5;
            @Override
            public void run() {
                int value = 10;
                System.out.println(this.value);
            }
        };
        r.run();
    }
}

public static void main(String[] args) {
    MeaningOfThis m = new MeaningOfThis();
    m.doIt();
    // 5
}

람다 사용

List<Apple> result = filterApples(inventory, (Apple apple) -> RED.equals(apple.getColor()));