C# design pattern suggestions

后端 未结 3 735
北海茫月
北海茫月 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:32

    You could start with implementations of something like this for each filter:

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

    For the sub-layer of filters (Condition 1...n) you could use a Composite 'all' filter like this; all of the IFilter implementations contained have to match for the composite to say it matches:

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

    ...and for the top-level of filters (if Condition n doesn't match check Condition n+1) you could combine multiple AllMatchingCompositeFilters in an 'any' filter like this; it executes each of its IFilters in the order they were added and returns true if any of them match:

    public class AnyMatchingCompositeFilter : List>, IFilter
    {
        public bool Matches(T itemToMatch)
        {
            return this.Any(filter => filter.Matches(itemToFilter));
        }
    }
    

提交回复
热议问题