当一个方法有多个实现方式的时候,例如生成文件有pdf,word,excel,这时候就可以采用这种方法。
首先声明一个需要实现方法的接口。
public interface FileInterface {
String WORD_FILE = "word";
String EXCEL_FILE = "word";
String PDF_FILE = "word";
String createFileByType(JSONObject data, OutputStream os);
}
实现这个接口。
public class WordFileImpl implements FileInterface {
@Override
public String createFileByType(JSONObject data, OutputStream os) {
return WORD_FILE;
}
}
生命一个工厂类
public class FileFactory {
private final ApplicationContext context;
public FileFactory(ApplicationContext context) {
this.context = context;
}
public FileInterface get(String type){
Map<String, FileInterface> filePreviewMap = context.getBeansOfType(FileInterface.class);
if (StringUtils.isEmpty(FileTypeEnum.getValueByName(type))){
throw new RuntimeException("不支持生成该类型文件");
}
return filePreviewMap.get(FileTypeEnum.getValueByName(type));
}
}
还需要一个枚举类来保存这些实现类名称,方便map查询。
public enum FileTypeEnum {
//word文件,实现类首字母小写
WORD("word","wordFileImpl"),
//pdf件p
PDF("pdf","pdfFileImepl"),
//excel文件
EXCEL("excel","excelFileImpl")
;
private final String instanceName;
private final String instanceValue;
FileTypeEnum(String instanceName, String instanceValue) {
this.instanceName = instanceName;
this.instanceValue = instanceValue;
}
public static String getValueByName(String instanceName){
for (FileTypeEnum fileType : FileTypeEnum.values()){
if (Objects.equals(fileType.instanceName,instanceName)){
return fileType.instanceValue;
}
}
return "";
}
}
当要使用方法时,直接调用factory.get()方法就可以获取具体的接口实现类。
然后 fileInterface.createFile();