Java 创建方法过滤器

Java 创建方法过滤器,java,language-agnostic,filter,Java,Language Agnostic,Filter,在我的代码中有一个列表。此列表中对象的属性可能包括以下内容: 身份证 名字 姓 在我的应用程序中,我将允许用户通过使用这三个值的任意组合来搜索特定的人。目前,我有一个switch语句,它只是检查填写了哪些字段,并调用为这些值的组合指定的方法 i、 e: 等等。实际上有7种不同的类型 这使我对每个语句都有一个方法。这是一种“好”的方法吗?有没有一种方法可以让我使用参数或某种“过滤器”?这可能没有什么区别,但我用Java编写了这段代码。您可以通过地图和界面做一些更为出色的事情。举个例子 inte

在我的代码中有一个
列表
。此列表中对象的属性可能包括以下内容:

  • 身份证
  • 名字
在我的应用程序中,我将允许用户通过使用这三个值的任意组合来搜索特定的人。目前,我有一个switch语句,它只是检查填写了哪些字段,并调用为这些值的组合指定的方法

i、 e:

等等。实际上有7种不同的类型


这使我对每个语句都有一个方法。这是一种“好”的方法吗?有没有一种方法可以让我使用参数或某种“过滤器”?这可能没有什么区别,但我用Java编写了这段代码。

您可以通过地图和界面做一些更为出色的事情。举个例子

interface LookUp{
    lookUpBy(HttpRequest req);
}

Map<Integer, LookUp> map = new HashMap<Integer, LookUp>();

map.put(0, new LookUpById());
map.put(1, new LookUpByIdAndName());
通过这种方式,您可以使用地图快速查找方法。当然,您也可以使用长开关,但我觉得这更易于管理

如果good的意思是“语言为我服务”,那么就不是


如果good表示“可读”,我将亲自定义一个方法match(),如果对象符合您的搜索条件,该方法将返回true。另外,可能是创建方法条件的一种好方法,您可以在其中封装搜索条件(您要查找哪些字段和哪些值)并将其传递给匹配(条件条件条件)。

这种方法很快变得难以管理,因为组合的数量很快变得巨大。 创建具有所有可能查询参数的PersonFilter类,并访问列表中的每个人:

private class PersonFilter {
    private String id;
    private String firstName;
    private String lastName;

    // constructor omitted

    public boolean accept(Person p) {
        if (this.id != null && !this.id.equals(p.getId()) {
            return false;
        }
        if (this.firstName != null && !this.firstName.equals(p.getFirstName()) {
            return false;
        }
        if (this.lastName != null && !this.lastName.equals(p.getLastName()) {
            return false;
        }

        return true;
    }
}
过滤现在由

public List<Person> filter(List<Person> list, PersonFilter filter) {
    List<Person> result = new ArrayList<Person>();
    for (Person p : list) {
        if (filter.accept(p) {
            result.add(p);
        }
    }
    return result;
}
公共列表过滤器(列表列表,个人过滤器过滤器){
列表结果=新建ArrayList();
用于(人员p:列表){
如果(过滤器接受(p){
结果:添加(p);
}
}
返回结果;
}

在某种程度上,你应该看看这样的东西,它将为这种类型的搜索提供最佳的可伸缩性、可管理性和性能。不知道你处理的数据量,我建议将其用于一个具有更大搜索对象集的长期解决方案。这是一个了不起的工具!

private class PersonFilter {
    private String id;
    private String firstName;
    private String lastName;

    // constructor omitted

    public boolean accept(Person p) {
        if (this.id != null && !this.id.equals(p.getId()) {
            return false;
        }
        if (this.firstName != null && !this.firstName.equals(p.getFirstName()) {
            return false;
        }
        if (this.lastName != null && !this.lastName.equals(p.getLastName()) {
            return false;
        }

        return true;
    }
}
public List<Person> filter(List<Person> list, PersonFilter filter) {
    List<Person> result = new ArrayList<Person>();
    for (Person p : list) {
        if (filter.accept(p) {
            result.add(p);
        }
    }
    return result;
}