1, 通過定義不同的謂詞介面來區分不同的蘋果的重量,如果後續有更多的需求,只需要添加更多的謂詞即可 package org.example; import java.util.ArrayList; import java.util.List; enum Color { RED, GREEN, YEL ...
1, 通過定義不同的謂詞介面來區分不同的蘋果的重量,如果後續有更多的需求,只需要添加更多的謂詞即可
package org.example;
import java.util.ArrayList;
import java.util.List;
enum Color {
RED, GREEN, YELLOW
}
class Apple {
private Integer weight;
private Color color;
public Apple(Integer weight, Color color) {
this.weight = weight;
this.color = color;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
}
interface ApplePredicate {
boolean test(Apple apple);
}
class AppleGreenColorPredicate implements ApplePredicate {
// 選擇綠色蘋果的謂詞
@Override
public boolean test(Apple apple) {
return Color.GREEN.equals(apple.getColor());
}
}
class AppleHeavyWeightPredicate implements ApplePredicate {
// 選擇重量大於150克的謂詞
@Override
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
}
public class Main {
public static List<Apple> filterApples(List<Apple> inventory, ApplePredicate p) {
// 通過謂詞篩選蘋果
List<Apple> result = new ArrayList<>();
for (Apple apple :
inventory) {
if (p.test(apple)) {
result.add(apple);
}
}
return result;
}
public static void main(String[] args) {
List<Apple> inventory = new ArrayList<>();
inventory.add(new Apple(300,Color.RED));
inventory.add(new Apple(12,Color.RED));
inventory.add(new Apple(350,Color.GREEN));
inventory.add(new Apple(200,Color.YELLOW));
// 方便的篩選綠色蘋果和重蘋果
List<Apple> result = filterApples(inventory, new AppleGreenColorPredicate());
result = filterApples(result, new AppleHeavyWeightPredicate());
for (var apple :
result) {
System.out.println(apple.getColor() + ":" + apple.getWeight());
}
}
}
2,上述定義介面實現的方式過於啰嗦和繁雜可以使用匿名類和lamble表達式進行簡化
2.1, 匿名內部類
List<Apple> result = filterApples(inventory, new ApplePredicate() {
@Override
public boolean test(Apple apple) {
return Color.GREEN.equals(apple.getColor());
}
});
result = filterApples(inventory, new ApplePredicate() {
@Override
public boolean test(Apple apple) {
return apple.getWeight() > 150;
}
});
2.2 lamble表達式
List<Apple> result = filterApples(inventory, (Apple apple)->apple.getColor().equals(Color.GREEN));
result = filterApples(result, (Apple apple)->apple.getWeight()>150);
3,更進一步的可以將針對蘋果的list類型進行抽象化,用於其他的水果
interface Predicate <T>{
boolean test(T t);
}
public static <T> List<T> filter(List<T> inventory, Predicate<T> p) {
// 通過謂詞篩選T
List<T> result = new ArrayList<>();
for (T e :
inventory) {
if (p.test(e)) {
result.add(e);
}
}
return result;
}