design-patterns - C# 设计模式建议

标签 design-patterns

我有一个对象集合。在此集合中,我需要使用多种条件搜索某个对象的出现。即。

使用条件 1 搜索

如果条件 1 失败使用条件 2

如果条件 2 失败使用条件 3

如果条件 3 失败使用条件 4

这些条件中的每一个都包含许多过滤器。

我正在寻找有关可维护的设计模式的建议。示例实现将不胜感激。

最佳答案

看起来像责任链:

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

In Object Oriented Design, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.

不要太在意“命令对象”这件事。 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
          )
        )
      )
    )
  }
};

关于design-patterns - C# 设计模式建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13643411/

相关文章:

c# - DDD 中的服务和存储库 (C#)

design-patterns - 可以用工厂代替单例吗?

performance - 原型(prototype)与享元

PHP 设计模式 : Multiple websites inside one script

java - 类设计——避免冗余代码

c++ - 对象池的替代方案?

java - 命令模式与反射

c# - 时间耦合与工作单元

c++ - 如何实现 Cloneable 类?

php - 在 PHP 中实现注册表模式的可扩展方式?