Abstraction of code from two methods in Java, perhaps using delegates?

I have two methods that do almost the same thing, only with different types. I want to abstract this functionality into some general method, and I think I could do it easily in C # with delegates, but I don't know the equivalent in Java. I am just showing two methods here, but there are several (e.g. eight) different makeWhateverRequest-style methods . Here are my methods:

public State makeGetRequest(User user, String name) {
    Get request = Builder.getGetRequest(user, name);
    GetResponse response = service.get(request);
    return ResponseTypeFactory.getResponseType(response);
}

public State makePutRequest(User user, String name) {
    Put request = Builder.getPutRequest(user, name);
    PutResponse response = service.put(request);
    return ResponseTypeFactory.getResponseType(response);
}

If there can be some delegate-like thing that accepts Userand String(as in the first line of each method), this will make the abstract line abstract for the general method. However, note that the first line returns a different value (i.e., an instance of either Get, or Put), and this value is used in the second line. The last line of each method is already the same and uses polymorphism to figure out which version to getResponseTypeinvoke to make it beautiful.

, . , - , Get, Put, - , . , , GetResponse PutResponse , , getResponseType, .

Get Put Request. GetResponse PutResponse Response. , , , , , , , .

Java, , #. .

: , :

IRequest              IResponse
|     \                |     \
Get   Put       GetResponse  PutResponse

:

Builder.getRequest(User, String)
=> IRequest

service.getPut(IRequest)
=> IResponse

ResponseTypeFactory.getResponseType(IResponse)
=> State
+3
4

, Java , . - , . 3 , , . , .

+2

Java , .

- , . Builder.getRequest, , , Get Put , ( "" "" ).

, Dependency Injection Builder ResponseTypeFactory.

+1

enum switch.

:

public enum RequestMethod { GET, PUT /* Add remaining here */ };

public State makeRequest(RequestMethod method, User user, String name) {
    Object response;
    switch (method) {
        case GET:
            response = service.get(Builder.getGetRequest(user, name));
            break;
        case PUT:
            response = service.put(Builder.getPutRequest(user, name));
            break;
        // Add remaining cases here.
    }
    return ResponseTypeFactory.getResponseType(response);
}
0

I have implemented callback / delegate support in Java using reflection. Details and a working source are available on my website . This will match what you are trying to do.

0
source

Source: https://habr.com/ru/post/1727122/


All Articles