Java重构类具有相同的方法
我对重构类的任何建议,所有静态方法都是相同的,只有一个变量代码
是不同的。
public class SuccessResponseBuilder {
static ResponseCode code = ResponseCode.OK;
public static <T> @NotNull ResponseBean build() {
return ResponseBean.builder(code, null);
}
public static <T> ResponseBean build(T data) {
return ResponseBean.builder(code, data);
}
}
public class ErrorResponseBuilder {
static ResponseCode code = ResponseCode.ERROR;
public static <T> @NotNull ResponseBean build() {
return ResponseBean.builder(code, null);
}
public static <T> ResponseBean build(T data) {
return ResponseBean.builder(code, data);
}
}
客户端将使用这种方式获取结果
errorresponsebuilder.build(e.getMessage());
successresponsebuilder.build(“ ok”);
Any suggestions for me to refactor the class, all the static methods are the same, only one of the variable code
is different.
public class SuccessResponseBuilder {
static ResponseCode code = ResponseCode.OK;
public static <T> @NotNull ResponseBean build() {
return ResponseBean.builder(code, null);
}
public static <T> ResponseBean build(T data) {
return ResponseBean.builder(code, data);
}
}
public class ErrorResponseBuilder {
static ResponseCode code = ResponseCode.ERROR;
public static <T> @NotNull ResponseBean build() {
return ResponseBean.builder(code, null);
}
public static <T> ResponseBean build(T data) {
return ResponseBean.builder(code, data);
}
}
The client will used this way to get the result
ErrorResponseBuilder.build(e.getMessage());
SuccessResponseBuilder.build("ok");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一种灵活,干净的方法。主要想法是创建内部
Builder
类。优势是您可以简单地添加一个新的wendersecode
而无需创建新类。用法:
输出将是
Here is a flexible, clean approach. The main idea is creating an inner
Builder
class. The advantage is you can simply add a newResponseCode
without creating new class.Usage:
Output will be