💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 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; } } ```