多实现方法的优雅使用

当一个方法有多个实现方式的时候,例如生成文件有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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值