资讯详情

设计模式【七】- 过滤器模式

1. 原理

界面方法的定义

过滤方法是根据不同的规则定义

创建过滤实例,调用过滤方法过滤数据

2. 代码

2.1 过滤对象Person

覆写hashCode和equals,去重使用

import java.util.Objects;  /**  * @description:  * @author: pp_lan  * @date: 2022/3/18  */ public class Person {      /**      * 姓名      */     private String name;      /**      * 是否男性      */     private boolean male;      /**      * 是否单身      */     private boolean single;      public Person() {     }      public Person(String name, boolean male, boolean single) {         this.name = name;         this.male = male;         this.single = single;     }      public String getName() {         return name;     }      public void setName(String name) {         this.name = name;     }      public boolean isMale() {         return male;     }      public void setMale(boolean male) {         this.male = male;     }      public boolean isSingle() {         return single;     }      public void setSingle(boolean single) {         this.single = single;     }       @Override     public boolean equals(Object o) {         if (this == o) {             return true;         }         if (o == null || getClass() != o.getClass()) {             return false;         }         Person person = (Person) o;         return male == person.male &&                 single == person.single &&                 Objects.equals(name, person.name);     }      @Override     public int hashCode() {         return Objects.hash(name, male, single);     }      @Override     public String toString() {         return this.name   "{"   this.male   ", "   this.single   "}";     } } 

2.2 过滤规则接口

import com.hz.design.filter.Person;  import java.util.List;  /**  * @description: 判定规则  * @author: pp_lan  * @date: 2022/3/18  */ public interface Rule {      /**      * 过滤      * @param personList      * @return      */     List<Person> filter(List<Person> personList); } 

2.3 规则实现类

2.3.1 男性过滤器

import com.hz.design.filter.Person;  import java.util.ArrayList; import java.util.List;  /**  * @description:  * @author: pp_lan  * @date: 2022/3/18  */ public class MaleRule implements Rule {      @Override     public List<Person> filter(List<Person> personList) {          // 过滤出男性         List<Person> resultList = new ArrayList<>();         personList.forEach(p -> {             if (p.isMale()) {                 resultList.add(p);             }         });          return resultList;     } }

2.3.2 女性过滤器

import com.hz.design.filter.Person;  import java.util.List; import java.util.stream.Collectors;  /**  * @description:  * @author: pp_lan  * @date: 2022/3/18  */ public class FeMaleRule implements Rule {      @Override     public List<Person> filter(List<Person> personList) {         // 过滤出女性         return personList.stream().filter(p -> !p.isMale()).collect(Collectors.toList());     } }

2.3.3 单身过滤器

import com.hz.design.filter.Person;  import java.util.List; import java.util.stream.Collectors;  /**  * @description:  * @author: pp_lan  * @date: 2022/3/18  */ public class SingleRule implements Rule {      @Override     public List<Person> filter(List<Person> personList) {         return personList.stream().filter(p -> p.isSingle()).collect(Collectors.toList());     } } 

2.3.4 规则And连接器

import com.hz.design.filter.Person;  import java.util.List;  /**  * @description:  * @author: pp_lan  * @date: 2022/3/18  */ public class AndRule implements Rule {      private Rule[] rules;       public AndRule(Rule... rules) {         if (rules == null) {             throw new IllegalArgumentException("规则不能为空");         }         this.rules = rules;     }      @Override     public List<Person> filter(List<Person> personList) {         List<Person> result = personList;         for (Rule rule : this.rules) {             result = rule.filter(result);         }          return result;     } }

2.3.5 规则Or连接器

import com.hz.design.filter.Person;  import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;  /**  * @description:  * @author: pp_lan  * @date: 2022/3/18  */ public class OrRule implements Rule {      private Rule[] rules;      public OrRule(Rule... rules) {         if (rules == null) {             throw new IllegalArgumentException("规则不能为空");         }         this.rules = rules;     }      @Override     public List<Person> filter(List&l;Person> personList) {
        Set<Person> result = new HashSet<>();
        for (Rule rule : this.rules) {
            result.addAll(rule.filter(personList));
        }

        return new ArrayList<>(result);
    }
}

2.4 测试类

import com.hz.design.filter.rule.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: pp_lan
 * @date: 2022/3/18
 */
public class FilterTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(FilterTest.class);

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("zhangsan", true, true));
        personList.add(new Person("liming", false, true));
        personList.add(new Person("chenshifou", false, false));
        personList.add(new Person("limingming", false, true));
        personList.add(new Person("jinli", true, false));
        personList.add(new Person("yinhaiguang", true, true));
        personList.add(new Person("yaoshuai", true, false));

        // 男性过滤器
        MaleRule maleRule = new MaleRule();

        // 女性过滤器
        FeMaleRule feMaleRule = new FeMaleRule();

        // 单身过滤器
        SingleRule singleRule = new SingleRule();


        List<Person> maleList = maleRule.filter(personList);
        List<Person> feMaleList = feMaleRule.filter(personList);

        List<Person> singleList = singleRule.filter(personList);

        LOGGER.info("男性:{}", maleList);
        LOGGER.info("女性:{}", feMaleList);
        LOGGER.info("单身:{}", singleList);

        AndRule maleSingleRule = new AndRule(maleRule, singleRule);
        AndRule femaleSingleRule = new AndRule(feMaleRule, singleRule);

        List<Person> maleSingleList = maleSingleRule.filter(personList);
        List<Person> femaleSingleList = femaleSingleRule.filter(personList);

        LOGGER.info("单身男性:{}", maleSingleList);
        LOGGER.info("单身女性:{}", femaleSingleList);

        OrRule allRule = new OrRule(maleRule, feMaleRule, singleRule);
        List<Person> allList = allRule.filter(personList);
        LOGGER.info("男性及非男性及单身:{}", allList);

    }
}

3. 执行结果

Connected to the target VM, address: '127.0.0.1:52917', transport: 'socket'
[2022-03-18 17:21:12,387] INFO  [main] c.h.d.f.FilterTest.main(44): 男性:[zhangsan{true, true}, jinli{true, false}, yinhaiguang{true, true}, yaoshuai{true, false}]
[2022-03-18 17:21:12,390] INFO  [main] c.h.d.f.FilterTest.main(45): 女性:[liming{false, true}, chenshifou{false, false}, limingming{false, true}]
[2022-03-18 17:21:12,390] INFO  [main] c.h.d.f.FilterTest.main(46): 单身:[zhangsan{true, true}, liming{false, true}, limingming{false, true}, yinhaiguang{true, true}]
[2022-03-18 17:21:12,391] INFO  [main] c.h.d.f.FilterTest.main(54): 单身男性:[zhangsan{true, true}, yinhaiguang{true, true}]
[2022-03-18 17:21:12,391] INFO  [main] c.h.d.f.FilterTest.main(55): 单身女性:[liming{false, true}, limingming{false, true}]
[2022-03-18 17:21:12,392] INFO  [main] c.h.d.f.FilterTest.main(59): 男性及非男性及单身:[zhangsan{true, true}, jinli{true, false}, liming{false, true}, limingming{false, true}, yinhaiguang{true, true}, yaoshuai{true, false}, chenshifou{false, false}]
Disconnected from the target VM, address: '127.0.0.1:52917', transport: 'socket'

4. 说明

rule实现了一定过滤规则,对list进行过滤;

AndRule会对规则进行叠加

OrRule对对规则结果合并

设计模式【八】-装饰器模式

标签: lan的连接器装饰连接器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台