C# design pattern suggestions

后端 未结 3 733
北海茫月
北海茫月 2021-01-21 02:48

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

3条回答
  •  隐瞒了意图╮
    2021-01-21 03:37

    It looks like Chain of Responsibility:

    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.

    Don't get hung up too much on the "command objects" thing. The core of CoR pattern is that it's a chain of objects that either handle the work themselves, or pass it on to the next one in the chain.

    Implementation:

    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
              )
            )
          )
        )
      }
    };
    

提交回复
热议问题