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