今天看到一块switch代码,觉得又臭又长,可以优化一下,只需要将函数名作为入参进行改造,有点类似于策略模式。
以下是使用Java8进行行为参数化的简单案例:
User.java
import lombok.Data; import lombok.ToString; @Data @ToString public class User { public User(Integer age) { this.age = age; } private Integer age; }
UserPredicate.java
public interface CommonPredicate<T> { boolean test(T t); }
Filter.java
import java.util.ArrayList; import java.util.List; public class Filter { /** * list 类型抽象化 * * @param list * @param p * @param <T> * @return */ public static <T> List<T> filter(List<T> list, CommonPredicate<T> p) { List<T> result = new ArrayList<T>(); for (T t : list) { if (p.test(t)) { result.add(t); } } return result; } public List<User> oldUser(List<User> inventory) { return filter(inventory, (User user) -> user.getAge() > 50); } public List<User> youngUser(List<User> inventory) { return filter(inventory, (User user) -> user.getAge() < 20); } public static void main(String[] args) { List<User> userList = new ArrayList<>(); userList.add(new User(11)); userList.add(new User(21)); userList.add(new User(31)); userList.add(new User(41)); userList.add(new User(51)); userList.add(new User(61)); Filter filter = new Filter(); List<User> oldList = filter.oldUser(userList); oldList.forEach(r -> System.out.println(r.toString())); System.out.println("======="); List<User> youngerList = filter.youngUser(userList); youngerList.forEach(y -> System.out.println(y.toString())); } }
Filter.java里面的main方法的输出结果如下:
User(age=51) User(age=61) ======= User(age=11)