【问题标题】:I want to implement an interface for a search class what is the best approach to implement an interface?我想为搜索类实现接口什么是实现接口的最佳方法?
【发布时间】:2012-05-31 07:44:08
【问题描述】:

我想要一个包含多个不同选项的搜索类,我的搜索类应该能够以不同的方式过滤结果,例如:

getX()
getY()
getZ()
getK()

X、Y、Z、K 以上是我的标准,它们在我的情况下很常见,所以我决定创建一个如下界面:

public interface IFilter {

public String getX();
public void setX(String x);
.
.
.

//I am not sure about the return type of my criteria!
public IAmNotSureAboutReturnType criteria();
}

应用程序每次都应该能够获得 1 个或多个条件,我的想法是有一个接口来指示一个类实现所有条件和一个条件()方法来将编译的条件返回给我的搜索类。

所有条件都基于字符串,但我不确定条件()的返回类型,因为它应该结合所有给定的条件并返回一个特定类型作为返回值。

我的搜索类不是基于 SQL,它主要基于 JSON。

谁能建议我为搜索类提供标准接口的最佳方法是什么?

【问题讨论】:

  • 请尝试使用代码格式化
  • 您将如何使用返回的条件?如果您要再次解析它并查看是否设置了 x 以及它的值是什么,那么为什么不为设置的条件返回一个映射呢?如果返回类型应该是可以按原样执行的查询,则创建这样的查询类(或接口)。确切的实现取决于您如何搜索 JSON 数据(您使用的 JSON 库、数据的格式等)。

标签: java design-patterns ooad


【解决方案1】:

也许访问者模式将有助于过滤器的实现:

public interface IFilter<T> {

    /**
    * This method will be called by filtering mechanizm. If it return true - item 
    * stay in resul, otherwise item rejected
    */
    boolean pass(T input);

}

您可以创建组合多个过滤器的 AND 和 OR 过滤器:

public class AndFilter<T> implements IFilter<T> {

    private final List<IFilter<T>> filters;

    public AndFilter(List<IFilter<T>> filters) {
        this.filter = filter;
    }

    @Override
    public boolean pass(T input) {
        for(IFilter<T> filter : filters) {
            if(!filter.pass(input)) {
                return false;
            }
        }
        return true;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 2021-08-23
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    相关资源
    最近更新 更多