【乐企文件生成工程】根据特定要素动态选择需要生成的发票板式文件实现

发布于:2025-02-11 ⋅ 阅读:(47) ⋅ 点赞:(0)

乐企版式文件生成工程,涉及到多个票种,不乏特殊票种的生成,如果每个特殊票种都单独写逻辑,那整个代码写起来体量就不得了,如何实现代码逻辑的同时也更优雅的实现代码扩展性呢,您接着往下看。

使用设计模式

工厂模式

1、定义接口InvoiceFileService
public interface InvoiceFileService {
    /**
     * 创建发票文件
     */
    <T extends BaseUploadInvoiceReq> BaseResp makeInvoiceFile(T invoiceData);

    /**
     * 获取特定要素类型
     */
    String getTdysKey();
}
2、具体的发票票种实现该接口

在这里插入图片描述

2.1、在实现类里实现对应的getTdysKey()方法
  @Override
    public String getTdysKey() {
        return InvoiceTagEnum.BASE_INVOICE.getCode();
    }
3、编写工厂类InvoiceFileFactory
package com.lq.invoice.factory;

import com.lq.invoice.service.file.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * User: yanjun.hou
 * Date: 2024/10/19 19:15
 * Description:
 */
@Component
public class InvoiceFileFactory {
    private final Map<String, InvoiceFileService> strategyMap;

    //初始化加载所有板式文件生成实现
    @Autowired
    public InvoiceFileFactory(List<InvoiceFileService> strategies) {
        this.strategyMap = strategies.stream()
                .collect(Collectors.toMap(
                        InvoiceFileService::getTdysKey,
                        Function.identity(),
                        (existing, replacement) -> existing // 防止重复键冲突
                ));
    }

    public InvoiceFileService getInvoiceFileService(String tdys) {
        return Optional.ofNullable(strategyMap.get(tdys))
                .orElseThrow(() -> new IllegalArgumentException("No strategy found for tdys: " + tdys));
    }
}

4、具体用法

    @resource 
    InvoiceFileFactory invoiceFileFactory;
    
    public BaseResp makeInvoiceFile(String tdys) {
    //参数省略
        return invoiceFileFactory.getInvoiceFileService(tdys).makeInvoiceFile(baseUploadInvoiceReq);
    }

网站公告

今日签到

点亮在社区的每一天
去签到