一、简述
1.1问题描述
在我们平时阅读源码时,经常会看到Result之类的,尤其是当它写了一串:Result.<List< String>>builder().success().data(stringList).build() 就很蒙。
这类的代码乍一看好像很高大上,其实究其本质就是java设计模式和静态内部类的使用。
1.2疑惑
java设计模式?有用吗?感觉自己写代码写业务的时候没有用到啊?如果说你平时写的代码业务是外功,那么java设计模式就是你要修的内功。对待技术,不能只是停留在使用层面,而要透过现象看其本质。下边就聊聊java设计模式中的建造者模式。
1.3java设计模式建造者模式
至于概念这里就不再赘述,为什么要使用建造者模式?主要用来构建复杂对象的【具体概念及详细参考:】,其次就是用来装一下【你懂的】。
下边参考详细代码,进行解释:
Result< T >
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
@Data
public class Result<T> {
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModelProperty(value = "请求说明")
private final String result;
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModelProperty(value = "200正常500异常")
private final Integer code;
@JsonInclude(JsonInclude.Include.NON_NULL)
@ApiModelProperty(value = "消息说明")
private final String message;
@ApiModelProperty(value = "数据")
private final T data;
//为静态成员变量赋值
private Result(Builder<T> builder) {
this.result = builder.result;
this.code = builder.code;
this.message = builder.message;
this.data = builder.data;
}
//Java 静态方法的返回值泛型使用与调用
public static <T> Result.Builder<T> builder() {
return new Result.Builder<>();
}
public static class Builder<T> {
private String result;
private Integer code;
private String message;
private T data;
public Builder<T> code(Integer code) {
this.code = code;
return this;
}
public Builder<T> message(String message) {
this.message = message;
return this;
}
public Builder<T> result(String result) {
this.result = result;
return this;
}
public Builder<T> data(T data) {
this.data = data;
return this;
}
public Builder<T> success() {
this.result = "SUCCESS";
this.code = 200;
return this;
}
public Builder<T> fail() {
this.result = "FAILURE";
this.code = 500;
return this;
}
public Result<T> build() {
return new Result<>(this);
}
}
@JsonIgnore
public Boolean isFailed() {
return this.code == 500;
}
}
Java 静态方法的返回值泛型使用与调用
public static <T> Result.Builder<T> builder() {
return new Result.Builder<>();
}
泛型(generic)类型在 Java 中使用特别频繁, 尤其在各种集合类(Collection)中. 一般如果自定义的类要使用泛型, 那么需要在类定义的时候, 声明泛型, 如:
public class Result<T>{......}
那么, 如果想在类的静态方法里上使用泛型, 以及如何在调用的时候, 传入泛型类型呢?
1.静态方法上在 static 关键字之后, 声明泛型:
public static <T> Result.Builder<T> builder() {
return new Result.Builder<>();
}
2.调用静态方法在.之后, 方法之前:
List<String> stringList = null;
Result.<List<String>>builder().success().data(stringList).build();
测试类进行测试:
TestBuilder
public class TestBuilder(){
Result<String> build = Result.<String>builder().success().data("小kiki").build();
System.out.println(build);
}
//打印结果
Result(result=SUCCESS,code=200,message=null,data=小kiki)
总结:
1.使用建造者模式(Builder)来简化大对象的构造,提高代码的简洁性,同时提高使用者的编码体验。
2.那就是为了装X,哈哈!!!
3.以上看不懂的话,可以私聊或者参考本人写的这篇博客:https://blog.csdn.net/qq_38616503/article/details/111052937