3

I have a collection of objects. Out of this collection I need to search for an occurrence of an object using a number of conditions. ie.

Search using Condition 1

If Condition 1 Fails use Condition 2

If Condition 2 Fails use Condition 3

If Condition 3 Fails use Condition 4

Each of these conditions consists of a number of filters.

I'm looking for suggestions with regards to a design pattern that's maintainable. Sample implementations will be appreciated.

4

3 回答 3

3

它看起来像责任链:

http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern

在面向对象设计中,责任链模式是一种设计模式,由一个命令对象源和一系列处理对象组成。每个处理对象都包含定义它可以处理的命令对象类型的逻辑;其余的被传递给链中的下一个处理对象。还存在一种将新处理对象添加到该链末端的机制。

不要太纠结于“命令对象”的事情。CoR 模式的核心是它是一个对象链,它们要么自己处理工作,要么将其传递给链中的下一个对象。

执行:

public interface LinkInChain {
  boolean search(final Data data, final OnFound onFound);
}

public abstract class LinkInChainBase {
  final private LinkInChain nextLink;

  public LinkInChainBase(final LinkInChain nextLink) {
    this.nextLink = nextLink;
  }

  protected abstract innerSearch(final Data data, final OnFound onFound);

  public boolean search(final Data data, final OnFound onFound) {
    if (!innerSearch(data, onFound)) {
      return nextLink.search(data, onFound);
    }
  }
}

public class SearchFactory {

  private final LinkInChain lastLink = new LinkInChain() {
    public boolean search(final Data data, final OnFound onFound) {
      return false;
    }

  }

  public LinkInChain searchChain() {
    return new SearchUsingCond1(
      new SearchUsingCond2(
        new SearchUsingCond3(
          new SearchUsingCond4(
            lastLink
          )
        )
      )
    )
  }
};
于 2012-11-30T11:10:22.410 回答
0

感觉就像某种工厂的战略可能会让你走上正确的道路。

于 2012-11-30T10:58:14.120 回答
0

您可以从每个过滤器的类似实现开始:

public interface IFilter<T>
{
    bool Matches(T itemToMatch);
}

对于过滤器的子层(条件 1...n),您可以使用这样的复合“全部”过滤器;包含的所有IFilter<T>实现都必须匹配组合才能说它匹配:

public class AllMatchingCompositeFilter : List<IFilter<MyClass>>, IFilter<MyClass>
{
    public bool Matches(T itemToMatch)
    {
        return this.All(filter => filter.Matches(itemToFilter));
    }
}

...对于顶级过滤器(如果条件 n 不匹配检查条件 n+1),您可以AllMatchingCompositeFilter像这样在“任何”过滤器中组合多个 s;它IFilter<T>按照添加的顺序执行每个 s,如果其中任何一个匹配,则返回 true:

public class AnyMatchingCompositeFilter : List<IFilter<MyClass>>, IFilter<MyClass>
{
    public bool Matches(T itemToMatch)
    {
        return this.Any(filter => filter.Matches(itemToFilter));
    }
}
于 2012-11-30T11:06:08.827 回答