将2个请求类合并到一个类别的Java中的单个类中?
我有2个请求为createrequest
和updaterequest
。唯一的区别是,UpdatereQuest
中不需要某些字段。因此,我需要超载以下采用createrequest
的方法:
private void setRequest(CreateRequest request) {
IntegrationRequest intRequest = new IntegrationRequest();
intRequest.setLocationId(request.getLocationId());
intRequest.setApiToken(request.getApiToken());
// other setters and procedures
}
重载的方法是:
private void setRequest(UpdateRequest request) {
IntegrationRequest intRequest = new IntegrationRequest();
intRequest.setLocationId(request.getLocationId());
intRequest.setApiToken(request.getApiToken());
// other setters and procedures
}
这两种方法都是从同一类调用的,因此,我无法将请求作为通用方式传递。在这个场景中,我想知道是否有更好的方法而不是超载setRequest
为了使用单个方法而不是2种方法?
I have 2 requests as CreateRequest
and UpdateRequest
. The only difference is that, some fields are not required in the UpdateRequest
. For this reason, I need to overload the following method that takes CreateRequest
:
private void setRequest(CreateRequest request) {
IntegrationRequest intRequest = new IntegrationRequest();
intRequest.setLocationId(request.getLocationId());
intRequest.setApiToken(request.getApiToken());
// other setters and procedures
}
The overloaded method is this:
private void setRequest(UpdateRequest request) {
IntegrationRequest intRequest = new IntegrationRequest();
intRequest.setLocationId(request.getLocationId());
intRequest.setApiToken(request.getApiToken());
// other setters and procedures
}
Both method are called from the same class and for this reason, I cannot pass the requests as a generic way. In this scene, I am wondering if there is a better approach instead of overloading setRequest
in order to use a single method instead of 2 methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于
createrequest
和updaterequest
,使用接口又如何?那么,您只需要一个方法
setRequest
,该将请求作为参数的接口实现。您也可以将其与您的基类结合:
您的请求类的签名将是:
What about using an Interface for both
CreateRequest
andUpdateRequest
?Then you would only need one method
setRequest
which gets an interface implementation of Request as parameter.You can also combine it with your base class:
The signature of your Request classes then would be: