vendredi 27 novembre 2020

avoiding duplicate service calls java

I have got the below services:

AccountService class:

public class AccountService {
    public createAccount(argumentsList1);
    public closeAccount(argumentsList2);
    //many other methods
}

ServiceHandler class:

public class ServiceHandler {//ServiceHandler is singleton

    SavingsAccountService savingsAccountService;//SavingsAccountService implements AccountService

    LoanAccountService loanAccountService;//LoanAccountService implements AccountService

    public AccountService getService(boolean isSavings) {
        if(isSavings) {
            return savingsAccountService;
        } else {
            return loanAccountService;
        }
    }
}

Also, I have got many different types of services like ABCService, XYZService, etc.. which invoke ServiceHandler first to get the runtime object of AccountService and then invoke the respective method as shown in the below example:

ABCService class:

public class ABCService {
    public void process1(boolean isSavingsAccount, a, b, c, arguments..) {
        AccountService accountService = ServiceHandler.getService(isSavingsAccount);
        accountService.createAccount(argumentsList1);
    }
}

XYZService class:

public class XYZService {
    public void process2(boolean isSavingsAccount, d, e, f, argumemts...) {
        AccountService accountService = ServiceHandler.getService(isSavingsAccount);
        accountService.closeAccount(argumentsList2);
    }
}

There are many other services like PQRService (similar to ABCService, XYZService), etc.. Here, I did not like duplicating the call to the ServiceHandler.getService(isSavingsAccount) in all other services (like ABCService, etc..) first to get the handle and then further invoking the required methods createAccount(), closeAccount(), etc.. How can I expose the methods of AccountService through ServiceHandler itself (so that I can call createAccount() with a single line of code)? Note that ServiceHandler is a singleton class and should be threadsafe. Is there any specific design pattern that I can use to eliminate the above duplication?

Aucun commentaire:

Enregistrer un commentaire