使用不同的标准来过滤一组对象,通过逻辑运算的方式把他们解耦
Demo
"""过滤器模式"""class Person:def __init__(self, name, gender, marital_status):self.name = nameself.gender = genderself.marital_status = marital_statusdef __str__(self):return '我是str'def __repr__(self):return f"name:{self.name}, gender: {self.gender},martial_status:{self.marital_status}"class Criteria:def meet_criteria(self, persons: [Person]):raise NotImplementedErrorclass CriteriaMale(Criteria):def meet_criteria(self, persons: [Person]):return set(filter(lambda person: person.gender == 'Male', persons))class CriteriaFemale(Criteria):def meet_criteria(self, persons: [Person]):return set(filter(lambda person: person.gender == 'Female', persons))class CriteriaSingle(Criteria):def meet_criteria(self, persons: [Person]):return set(filter(lambda person: person.marital_status == 'Single', persons))class AndCriteria(Criteria):def __init__(self, criteria: Criteria, other_criteria: Criteria):self.criteria = criteriaself.other_criteria = other_criteriadef meet_criteria(self, persons: [Person]):return set(self.criteria.meet_criteria(persons)) & set(self.other_criteria.meet_criteria(persons))class OrCriteria(Criteria):def __init__(self, criteria: Criteria, other_criteria: Criteria):self.criteria = criteriaself.other_criteria = other_criteriadef meet_criteria(self, persons: [Person]):return set(self.criteria.meet_criteria(persons)) | set(self.other_criteria.meet_criteria(persons))if __name__ == '__main__':persons = [Person("Robert", "Male", "Single"),Person("John", "Male", "Married"),Person("Laura", "Female", "Married"),Person("Diana", "Female", "Single"),Person("Mike", "Male", "Single"),Person("Bobby", "Male", "Single"),]male = CriteriaMale()female = CriteriaFemale()single = CriteriaSingle()single_male = AndCriteria(male, single)single_or_female = OrCriteria(single, female)print(f"males:")print(male.meet_criteria(persons))print(f"female:")print(female.meet_criteria(persons))print(f"single:")print(single.meet_criteria(persons))print("single males:")print(single_male.meet_criteria(persons))print("single or females:")print(single_or_female.meet_criteria(persons))
