结构型模式-过滤器模式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Person { public int Age { get; set; } public string Name { get; set; } public Gender Gender { get; set; } public Person(int age, string name, Gender gender) { this.Age = age; this.Name = name; this.Gender = gender; } public override string ToString() { StringBuilder sb = new StringBuilder("Person{"); sb.AppendFormat("age={0},", this.Age); sb.AppendFormat("name='{0}',", this.Name); sb.AppendFormat("gender='{0}'}", this.Gender); return base.ToString(); } } public enum Gender { Male, Female }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public interface Filter { List<Person> filter(List<Person> people); } class AgeGreaterThan20Filter : Filter { public List<Person> filter(List<Person> people) { List<Person> result = new List<Person>(); foreach (var p in people) { if (p.Age > 20) { result.Add(p); } } return result; } } class FemaleFilter : Filter { public List<Person> filter(List<Person> people) { List<Person> result = new List<Person>(); foreach (var p in people) { if (p.Gender == Gender.Female) { result.Add(p); } } return result; } } class AndFilter : Filter { private Filter one; private Filter other; public AndFilter(Filter one, Filter other) { this.one = one; this.other = other; } public List<Person> filter(List<Person> people) { var temp = one.filter(people); return other.filter(temp); } }
static void Main(string[] args) { var people = new List<Person>(); people.Add(new Person(10,"Andy",Gender.Male)); people.Add(new Person(25, "Cady", Gender.Male)); people.Add(new Person(24, "Lazz", Gender.Female)); var and = new AndFilter(new AgeGreaterThan20Filter(), new FemaleFilter()); var p = and.filter(people); Console.Read(); }