mercredi 22 novembre 2023

Java Factory pattern

java spring boot : i have module A and module B each one have some specific services and i have a module c that don't have any dependencies to A and B so what i want is in module C i want to call services from module A or B i want to acheive that using factory pattern.

in module C i have this interface

public interface ThirdPartyCallsStrategy {
    void apply(String orderId);
}

and this is example of factory class

@Component
@AllArgsConstructor
public class CoreCallsFactory {

    private static final String A_PACKAGE = "com.testA.service";
    private static final String A_CLASS = "TestClassA";


    private static final String B_PACKAGE = "com.testB.service";
    private static final String B_CLASS = "TestClassA";


    @SneakyThrows
    public ThirdPartyCallsStrategy createThirdPartyCallsStrategy(String type) {

        Class<?> clazz;
        if (type.equals("A")) {
            clazz = Class.forName(String.format("%s.%s", A_PACKAGE , A_CLASS ));
            return (ThirdPartyCallsStrategy) clazz.getDeclaredConstructor().newInstance();
        }

        if (type.equals("B")) {
            clazz = Class.forName(String.format("%s.%s", B_PACKAGE , B_CLASS ));
            return (ThirdPartyCallsStrategy) clazz.getDeclaredConstructor().newInstance();
        }
        return null;
    }
}

ThirdPartyCallsStrategy is implemented in different services in different modules

And finally in module C, i make the instanciation through java reflective but this will be at runtime and i really appreciate cleaner way

`public String checkStatusAndRedirect(String orderId, String type) { boolean status = checkStatus(orderId); StringBuilder paymentResultUrl = new StringBuilder(frontUrl + "/public/payment/status?success=");

    if (status) {
        coreCallsFactory.createThirdPartyCallsStrategy(type).apply(orderId);
        paymentResultUrl.append(Boolean.TRUE);
    } else {
        paymentResultUrl.append(Boolean.FALSE);
    }
    return paymentResultUrl.toString();
}`

So what i need is a clean way and change this implementation

Aucun commentaire:

Enregistrer un commentaire