我有一个对象集合。在这个集合之外,我需要使用许多条件来搜索某个对象的匹配项。即。
使用条件1进行搜索
如果条件1失败,请使用条件2
如果条件2失败,请使用条件3
如果条件3失败,则使用条件4
这些条件中的每一个都由多个过滤器组成。
我正在寻找关于可维护的设计模式的建议。示例实现将不胜感激。
发布于 2012-11-30 19:10:22
这看起来像是一系列的责任:
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-30 18:58:14
感觉像是一个拥有某种工厂的战略可能会让你走上正确的道路。
发布于 2012-11-30 19:06:09
您可以从为每个过滤器实现以下内容开始:
public interface IFilter<T>
{
bool Matches(T itemToMatch);
}对于过滤器的子层(条件1...n),您可以使用像这样的组合' all‘过滤器;所有包含的IFilter<T>实现都必须匹配,这样组合才能说它匹配:
public class AllMatchingCompositeFilter : List<IFilter<MyClass>>, IFilter<MyClass>
{
public bool Matches(T itemToMatch)
{
return this.All(filter => filter.Matches(itemToFilter));
}
}...and对于顶级筛选器(如果条件n与检查条件n+1不匹配),您可以将多个AllMatchingCompositeFilter组合在一个' any‘筛选器中,如下所示;它按添加顺序执行每个IFilter<T>,如果它们中的任何一个匹配,则返回true:
public class AnyMatchingCompositeFilter : List<IFilter<MyClass>>, IFilter<MyClass>
{
public bool Matches(T itemToMatch)
{
return this.Any(filter => filter.Matches(itemToFilter));
}
}https://stackoverflow.com/questions/13643411
复制相似问题