jeudi 7 juillet 2022

How to combine similar Interfaces in Java?

In my Java (Spring Boot) app, I have the following service interface:

public interface PDFService {

    String createPdf(UUID uuid);
}

And the following service method as implementation:

public class BrandPDFServiceImpl implements PDFService {

    private final BrandService brandService;

    @Override
    public String createPdf(UUID uuid) {
        Context context = new Context();

        BrandDTO brandDTO = brandService.findByUuid(uuid);
        context.setVariable("name", brandDTO.getName());
        context.setVariable("url", brandDTO.getImageUrl());
        setProductInformationToHtml(context, uuid);
        return templateEngine.process("template", context);
    }
}

Now I need to implement a similar service that will use ProductService instead of BrandService:

public class ProductPDFServiceImpl implements PDFService {

    private final ProductService brandService;

    @Override
    public String createPdf(UUID uuid) {
        Context context = new Context();

        ProductDTO productDTO = productService.findByUuid(uuid);
        context.setVariable("name", productDTO.getName());
        context.setVariable("url", productDTO.getImageUrl());
        setProductInformationToHtml(context, uuid);
        return templateEngine.process("template", context);
    }
}

If I use this approach, I cannot call the proper implementation from Controller as shown below:

private final PDFService pdfService;


public String createBrandPdf(@PathVariable UUID uuid) {
    return pdfService.createPdf(uuid);
}


// Note: I will add another endpoint for Product, 
// but still cannot differentiate which service will be called :( 

public String createProductPdf(@PathVariable UUID uuid) {
    return pdfService.createPdf(uuid); // ???
}

In this scene, how should I merge these 2 service in a proper way? I think maybe I need to create 2 interface that inherits from PDFService, but not sure it there is a better way e.g. using Generic or Template Method Pattern. Any idea?

Aucun commentaire:

Enregistrer un commentaire