设计模式——工厂模式

目录

背景

实现


背景

虽然学习了设计模式,但在实际开发过程中好像很少使用。最近做一个文件上传、下载、删除功能,文件存储支持minio、fastDf(以后可能继续扩展),现场部署按资源情况决定使用哪种文件存储。  

实现

文件工厂类

文件基础接口

文件抽象类

minio文件实现类

fastDf文件实现类

(1)文件工厂类

@Service
public class FileFactory {

    public static final String czClassName = "FileCzServiceImpl";
    private static final Logger logger = LoggerFactory.getLogger(FileFactory.class);
    //可以是1是fastDf2是minio
    @Value("${fwqlx:1}")
    public Integer fwqlx;
    @Autowired
    private Map<String, FileCzService> fileCzServiceMap = new ConcurrentHashMap<>(2);


    public FileCzService getFileCzService(Integer fwqlx) {
        if (fwqlx == null) {
            fwqlx = this.fwqlx;
        }
        return fileCzServiceMap.get(FileFwqEnum.getMc(fwqlx) + czClassName);
    }


    public String uploadFile(File file) throws Exception {
        FileCzService fileCzService = getFileCzService(this.fwqlx);
        return fileCzService.uploadFile(file);
    }

 
    public String uploadFile(MultipartFile multipartFile) throws Exception {
        FileCzService fileCzService = getFileCzService(this.fwqlx);
        return fileCzService.uploadFile(multipartFile);
    }


  
    public byte[] downloadWithUrl(String fileUrl, Integer fwqlx) {
        FileCzService fileCzService = getFileCzService(fwqlx);
        return fileCzService.downloadWithUrl(fileUrl);
    }

 
    public boolean deleteFileWithUrl(String fileUrl, Integer fwqlx) {
        boolean result = false;
        try {
            FileCzService fileCzService = getFileCzService(fwqlx);
            result = fileCzService.deleteFileWithUrl(fileUrl);
        } catch (Exception e) {
            logger.error("删除文件出错,错误信息", e);
        }
        return result;
    }

}

 (2)文件服务器枚举类

public enum FileFwqEnum {
    FASTDF(1, "fastDf"),
    MINIO(2, "minio"),
    //TODO 继续扩展其他文件存储类型

    ;

    private final Integer bm;
    private final String mc;

    FileFwqEnum(Integer bm, String mc) {
        this.bm = bm;
        this.mc = mc;
    }

    public static String getMc(Integer bm) {
        if (null != bm) {
            for (FileFwqEnum ps : FileFwqEnum.values()) {
                if (bm.equals(ps.bm)) {
                    return ps.mc;
                }
            }
        }
        return StringUtils.EMPTY;
    }

    public Integer getBm() {
        return bm;
    }

    public String getMc() {
        return mc;
    }
}

(3)文件基础接口类


/**
 * 文件操作类
 */
public interface FileCzService {

    /**
     * @Description  文件上传
     **/
    String uploadFile(File file) throws Exception;

    /**

     * @Description  文件上传重载方法(无需转MultipartFile,适用于从前端上传文件)
     **/
    String uploadFile(MultipartFile multipartFile) throws Exception;


    /**
     * @Description  文件下载
     **/
    byte[] downloadWithUrl(String fileUrl);

    /**
     * @Description  文件删除
     **/
    boolean deleteFileWithUrl(String fileUrl);
}

(4)文件抽象类

@Component
public abstract class AbstractFileCzService implements FileCzService {

    private static final Logger logger = LoggerFactory.getLogger(AbstractFileCzService.class);

    // 生成文件类WWW
    protected MultipartFile getMultipartFile(File file) {
        FileItem item = createFileItem(file);
        MultipartFile multipartFile = null;
        try {
            multipartFile = new CommonsMultipartFile(item);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return multipartFile;
    }

    private FileItem createFileItem(File file) {
        FileItemFactory factory = new DiskFileItemFactory(16, null);
        FileItem item = factory.createItem("file", "application/pdf", true, file.getName());
        int bytesRead;
        byte[] buffer = new byte[8192];
        try (InputStream fis = Files.newInputStream(file.toPath());
             OutputStream os = item.getOutputStream()) {
            while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            logger.error(e.getMessage());
        }
        return item;
    }
}

(5)minio实现类

@Component
public class MinioFileCzServiceImpl extends AbstractFileCzService {

    private static final Logger logger = LoggerFactory.getLogger(MinioFileCzServiceImpl.class);

    @Autowired
    private MinioService minioService;



    @Override
    public String uploadFile(File file) {
        try {
            StorageFileInfo storageFileInfo = minioService.uploadFile(getMultipartFile(file));
            if (storageFileInfo != null) {
                logger.info("minio上传文件成功");
                return storageFileInfo.getObject();
            }
        } catch (Exception e) {
            logger.error("minio上传文件失败:{}", e.getMessage());
        }
        return "";
    }


    @Override
    public String uploadFile(MultipartFile multipartFile) {
        try {
            StorageFileInfo storageFileInfo = minioService.uploadFile(multipartFile);
            if (storageFileInfo != null) {
                logger.info("minio上传文件成功");
                return storageFileInfo.getObject();
            }
        } catch (Exception e) {
            logger.error("minio上传文件失败:{}", e.getMessage());
        }
        return "";
    }


    @Override
    public byte[] downloadWithUrl(String fileUrl) {
        return minioService.downloadWithObject(fileUrl);
    }


    @Override
    public boolean deleteFileWithUrl(String fileUrl) {
        return minioService.deleteObject(fileUrl);
    }
}

fastDfs实现类

@Component
public class FastDfFileCzServiceImpl extends AbstractFileCzService {

    private static final Logger logger = LoggerFactory.getLogger(FastDfFileCzServiceImpl.class);

    @Autowired
    private FastDFSClient fastDFClient;


    @Override
    public String uploadFile(File file) {
        try {
            StorageFileInfo storageFileInfo = fastDFClient.uploadFile(getMultipartFile(file));
            if (storageFileInfo != null) {
                logger.info("FastDFS上传文件成功,路径:{}", storageFileInfo.getUrlPath());
                return storageFileInfo.getUrlPath();
            }
        } catch (Exception e) {
            logger.error("FastDFS上传文件失败:{}", e.getMessage());
        }
        return "";
    }


    @Override
    public String uploadFile(MultipartFile multipartFile) {
        try {
            StorageFileInfo storageFileInfo = fastDFClient.uploadFile(multipartFile);
            if (storageFileInfo != null) {
                logger.info("FastDFS上传文件成功,路径:{}", storageFileInfo.getUrlPath());
                return storageFileInfo.getUrlPath();
            }
        } catch (Exception e) {
            logger.error("FastDFS上传文件失败:{}", e.getMessage());
        }
        return "";
    }


    @Override
    public byte[] downloadWithUrl(String fileUrl) {
        return fastDFClient.downloadWithUrl(fileUrl);
    }


    @Override
    public boolean deleteFileWithUrl(String fileUrl) {
        return fastDFClient.deleteFileWithUrl(fileUrl);
    }
}

如果以后要扩展文件存储类型,只需要新增一个类extends AbstractFileCzService,然后在文件服务枚举类增加枚举类型FileFwqEnum

相关推荐

  1. 设计模式工厂模式

    2024-04-23 18:42:02       69 阅读
  2. 设计模式--工厂模式

    2024-04-23 18:42:02       53 阅读
  3. 设计模式 工厂模式

    2024-04-23 18:42:02       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-23 18:42:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-23 18:42:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-23 18:42:02       82 阅读
  4. Python语言-面向对象

    2024-04-23 18:42:02       91 阅读

热门阅读

  1. Mixins 与 Extend:组件逻辑重用与扩展

    2024-04-23 18:42:02       34 阅读
  2. 基于POI封装的excel实用小工具

    2024-04-23 18:42:02       37 阅读
  3. fastjson

    2024-04-23 18:42:02       30 阅读
  4. 【华为OD机试】解密犯罪时间【C卷|100分】

    2024-04-23 18:42:02       31 阅读
  5. @Configuration 和 @Component 的区别

    2024-04-23 18:42:02       31 阅读
  6. Android中仿微信语音竖线动画2

    2024-04-23 18:42:02       28 阅读
  7. vue的双向数据绑定原理(v2、v3)

    2024-04-23 18:42:02       33 阅读
  8. YOLO的前世今生以及来龙去脉的背景介绍

    2024-04-23 18:42:02       34 阅读
  9. 设置失效时间失效的问题

    2024-04-23 18:42:02       32 阅读
  10. 算法刷题记录 Day50

    2024-04-23 18:42:02       31 阅读