zoukankan      html  css  js  c++  java
  • 过滤器模式

    最近开发的一个功能,要求读取一个目录,对目录下的文件名进行过滤。

    考虑到读取目录是一个独立的与文件操作相关的公共功能,与业务没有关系,而文件名的过滤条件是由不同的业务决定的,所以二者要做到逻辑上的隔离。因此想到针对不同的业务涉及不同的过滤器,文件目录读取工具类能够接受过滤器作为参数,而不必关心过滤器到底要过滤些啥东西。

    废话不多说,翠花,上代码:

    1、定义过滤器接口

    public interface FilterInterface{
        boolean accept(String name);
    }

    2、定义各式各样的过滤器

    public class Business1Filter implments FilterInterface {
        //业务1的过滤逻辑
        boolean accept(String name)
        {
            ......;
        }
    }
    
    public class Business2Filter implments FilterInterface {
        //业务2的过滤逻辑
        boolean accept(String name)
        {
            ......;
        }
    }

    3、在公共的文件操作类中,在对应的方法上添加过滤器参数

    public class DirManger{
       /*目录读取方法*/ List
    <String> ReadDir(String dirPath,FilterInterface[] filters){ File file = new File(dirPath); List<String> reslist = new ArrayList<String>(); String[] filelist = file.list(); for(String str : filelist) {//遍历文件 for(FilterInterface filter : filters){//对文件名进行过滤操作 if(filter.accept(str)){//返回通过过滤器的文件名 reslist.add(str); } } } return reslist } }

    4、具体的业务类中,就可以采用各式各样的过滤器组成数组,调用ReadDir方法,返回符合条件的文件名

    public class Business1{
        public List<String> getDirContent(path){
            FilterInterface[] business1Filter = {new Business1Filter()};//可以定义多个过滤器
            return DirManger.ReadDir(path,business1Filter);
        }
    }
  • 相关阅读:
    PostgreSQL 10编译安装(CentOS 7)
    CentOS安装单机Zookeeper
    [Oracle报错]TNS-12535: TNS:operation timed out、TNS-00505: Operation timed out
    hibernate一级缓存及对象的状态
    hibernate框架的简单入门
    Json和Ajax
    sql多行多列重复
    折线图饼状图柱形图
    XML文件的读取
    Json数据产生树形结构
  • 原文地址:https://www.cnblogs.com/mingziday/p/4604925.html
Copyright © 2011-2022 走看看