原文地址:https://jaune162.blog/design-pattern/abstract-factory-pattern/
引言
首先我们由一个实际问题来引出抽象工厂模式。
考虑这样一个场景,系统中需要向OSS上传文件,以及通过OSS下载文件。而在系统中有不同的业务在使用这两个功能。如下图:
伪代码如下
public interface FileUploader {/*** 上传文件** @param file 文件* @return 文件路径*/String uploadFile(File file);
}public interface FileDownloader {/*** 下载文件* @param path 文件路径* @return 文件流*/InputStream download(String path);
}@Slf4j
public class AliyunFileUploaderImpl implements FileUploader {@Overridepublic String uploadFile(File file) {log.info("向阿里云OSS上传文件");return "/test/" + file.getName();}
}@Slf4j
public class AliyunFileDownloaderImpl implements FileDownloader {@Overridepublic InputStream download(String path) {log.info("通过阿里云下载文件");// 这里只是模拟文件下载,所以不创建文件流,而是使用空文件流return ByteArrayInputStream.nullInputStream();}
}@Slf4j
public class XxxService1 {private final FileUploader fileUploader = new AliyunFileUploaderImpl();public void doService(File file) {String filePath = this.fileUploader.uploadFile(file);log.info("文件上传到了:{}", filePath);log.info("XxxService1 执行其他业务代码");}
}@Slf4j
public class XxxService2 {private final FileUploader fileUploader = new AliyunFileUploaderImpl();private final FileDownloader fileDownloader = new AliyunFileDownloaderImpl();public void doService1(File file) {String filePath = this.fileUploader.uploadFile(file);log.info(