ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
## 1.1 行为参数化的实现原理 > 以下程序的目的是对Model类型的列表进行多种方式的**过滤**,将满足条件的元素筛选出来。 ### 1.1.1 Model类 ```java public class Model { private int height; private String color; public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } } ``` ### 1.1.2 接口以及两种实现 ```java public interface Test { boolean test(Model model); } ``` ```java public class ColorTest implements Test{ @Override public boolean test(Model model) { return "red".equals(model.getColor()); } } ``` ```java public class HeightTest implements Test{ @Override public boolean test(Model model) { return model.getHeight() > 10; } } ``` ### 1.1.3 测试中的行为参数化 类似 `策略模式`,以下是行为参数化的测试程序: ```java import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<Model> modelList = new ArrayList<>(); List<Model> heightList = filter(modelList,new ColorTest()); List<Model> colorList = filter(modelList, new HeightTest()); } static List<Model> filter(List<Model> appleList, Test test) { List<Model> result = new ArrayList<>(); for (Model model : appleList) { if (test.test(model)) { result.add(model); } } return result; } } ```