构建者模式:主要用于对外提供统一的参数封装。
案例:Request 参数封装。
public class Request {
private String url;
private String method;
//私有化构造函数
private Request(Builder builder) {
this.url = builder.url;
this.method = builder.method;
}
//提供静态的Buidler构建器封装参数
public static Request.Builder builder() {
return new Builder();
}
@Override
public String toString() {
return "Request [url=" + url + ", method=" + method + "]";
}
//内部创建Builder构建器类,提供给外界设置参数
final static class Builder{
private String url;
private String method;
public Builder setUrl(String url) {
this.url = url;
return this;
}
public Builder setMethod(String method) {
this.method = method;
return this;
}
public Request build() {
return new Request(this);
}
}
//调用案例
public static void main(String[] args) {
Request request = Request.builder().
setMethod("POST")
.setUrl("http://baidu.com/")
.build();
System.out.println(request.toString());
}
}