Java 重构 类 有相同的方法

Java Refactor classes have same method

对我重构 class 的任何建议,所有静态方法都是相同的,只有一个变量 code 不同。

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");

这是一种灵活、干净的方法。主要思想是创建一个内部 Builder class。优点是您可以简单地添加一个新的 ResponseCode 而无需创建新的 class.

public class ResponseBean {

    private final ResponseCode code;
    private Object data;

    private ResponseBean(ResponseCode code) {
        this.code = code;
    }

    private ResponseBean(ResponseCode code, Object data) {
        this.code = code;
        this.data = data;
    }

    public static Builder ok() {
        return new Builder(ResponseCode.OK);
    }

    public static Builder error() {
        return new Builder(ResponseCode.ERROR);
    }

    /* if you would like to create a new ResponseCode:
    public static Builder yourNewCode() {
        return new Builder(ResponseCode.NEW_CODE);
    }
    */

    public static class Builder {

        private final ResponseCode code;

        public Builder(ResponseCode code) {
            this.code = code;
        }
        
        public ResponseBean build() {
            return new ResponseBean(code);
        }

        public ResponseBean build(Object data) {
            return new ResponseBean(code, data);
        }
    }
}

用法:

public void print() {
    ResponseBean okResponse = ResponseBean.ok().build("This is ok data");
    ResponseBean okResponseWithoutData = ResponseBean.ok().build();
    ResponseBean errorResponse = ResponseBean.error().build("This is error data");
    ResponseBean errorResponseWithoutData = ResponseBean.error().build();

    System.out.println(okResponse);
    System.out.println(okResponseWithoutData);
    System.out.println(errorResponse);
    System.out.println(errorResponseWithoutData);
}

输出将是

ResponseBean(code=OK, data=This is ok data)
ResponseBean(code=OK, data=null)
ResponseBean(code=ERROR, data=This is error data)
ResponseBean(code=ERROR, data=null)