过滤器模式

82 阅读2分钟

过滤器模式

过滤器模式或标准模式使用不同的标准来过滤一组对象。这种模式涉及到一个或多个标准,根据这些标准对对象集合进行逻辑操作(如AND、OR、NOT)来过滤出符合条件的对象。

案例:

有一个存储了员工信息的表,包括姓名、部门、薪资等。希望能够根据不同的标准(如部门、薪资范围等)来过滤员工记录。使用过滤器模式,为每种过滤条件创建不同的过滤器,然后组合使用这些过滤器来实现复杂的查询功能。

class Employee {
    private name: string;
    private department: string;
    private salary: number;
    constructor(name: string, department: string, salary: number) {
        this.name = name;
        this.department = department;
        this.salary = salary;
    }
    getName(): string {
        return this.name;
    }
    getDepartment(): string {
        return this.department;
    }
    getSalary(): number {
        return this.salary;
    }
}
//定义一个标准接口(Criteria)用于过滤员工
interface Criteria {
    meetCriteria(employees: Employee[]): Employee[];
}
//部门标准
class CriteriaDepartment implements Criteria {
    private department: string;
​
    constructor(department: string) {
        this.department = department;
    }
​
    meetCriteria(employees: Employee[]): Employee[] {
        return employees.filter(employee => employee.getDepartment() === this.department);
    }
}
//薪资标准
class CriteriaSalary implements Criteria {
    private minSalary: number;
    private maxSalary: number;
​
    constructor(minSalary: number, maxSalary: number) {
        this.minSalary = minSalary;
        this.maxSalary = maxSalary;
    }
​
    meetCriteria(employees: Employee[]): Employee[] {
        return employees.filter(employee => employee.getSalary() >= this.minSalary && employee.getSalary() <= this.maxSalary);
    }
}
//组合标准
class AndCriteria implements Criteria {
    private criteria: Criteria;
    private otherCriteria: Criteria;
​
    constructor(criteria: Criteria, otherCriteria: Criteria) {
        this.criteria = criteria;
        this.otherCriteria = otherCriteria;
    }
​
    meetCriteria(employees: Employee[]): Employee[] {
        let firstCriteriaItems = this.criteria.meetCriteria(employees);
        return this.otherCriteria.meetCriteria(firstCriteriaItems);
    }
}
let employees: Employee[] = [
    new Employee("John Doe", "IT", 6000),
    new Employee("Jane Doe", "HR", 7000),
    new Employee("Jim Beam", "IT", 5000),
    new Employee("Sara Smith", "HR", 8000),
];
​
let criteriaIT: Criteria = new CriteriaDepartment("IT");
let criteriaSalary: Criteria = new CriteriaSalary(5000, 7000);
let andCriteria: Criteria = new AndCriteria(criteriaIT, criteriaSalary);
​
let itEmployees = criteriaIT.meetCriteria(employees);
console.log("IT Department: ", itEmployees);
​
let salaryRangeEmployees = criteriaSalary.meetCriteria(employees);
console.log("Salary Range 5000-7000: ", salaryRangeEmployees);
​
let itAndSalaryRangeEmployees = andCriteria.meetCriteria(employees);
console.log("IT Department and Salary Range 5000-7000: ", itAndSalaryRangeEmployees);
​

这样设计可以灵活地根据不同的标准(部门、薪资范围等)来过滤员工数据,并且可以通过组合不同的标准来实现更复杂的过滤逻辑。这种方法提供了高度的灵活性和可扩展性,使得在处理复杂的查询需求时更加方便。