今天在研究Okhttp源码,看到Request类时发现该类使用Builder模式来构建Request,还有HttpUrl 、Okhttp等也使用了构建模式。
以下是根据Okhttp源码中的Request类模仿的模式。
package com.zghw.ack;
/**
* Created by zhanghw on 2017/9/7.
* Builder模式构建Request请求对象
* 为了可以在多线程中使用,定义为不可变类
* 这个方式在builder 构造好对象后,Request不可变。
*/
public final class Request {
final String method;
final String url;
//不提供默认new方法,让内部静态类Builder构建,主要进行copy
Request(Builder builder) {
this.method = builder.method;
this.url = builder.url;
}
//仅提供读方法
public String getMethod() {
return method;
}
//仅提供读方法
public String getUrl() {
return url;
}
/**
* 重新构建一个Builder对象,把当前request深度拷贝到新的对象中,
* 然后调用builder 修改或追加组件。
*
* @return
*/
public Builder newBuilder() {
return new Builder(this);
}
public static class Builder {
//字段一般和Request字段一样便于构建
String method;
String url;
//提供默认构造方法,创建对象一遍构建request
public Builder() {
this.method = "GET";
}
//构造是用来拷贝的已有的
Builder(Request request) {
this.method = request.method;
this.url = request.url;
}
//构建组件method
public Builder method(String method) {
this.method = method;
//返回当前Builder对象
return this;
}
//构建组件url
public Builder url(String url) {
this.url = url;
return this;
}
//组件构建最后构建Request,这里是把当前builder对象拷贝到Request对象中。
public Request build() {
if (url == null) {
throw new NullPointerException("url==null");
}
return new Request(this);
}
}
public static void main(String args[]) {
//链条式构建
Request request = new Request.Builder().method("POST").url("http:www.baidu.com").build();
//使用request重新构建一个新的Request对象,不存在添加或修改组件。
Request requestNew = request.newBuilder().method("DELETE").build();
System.out.println(request.toString() + "=" + request.getMethod() + " " + request.getUrl() + " , " + requestNew.toString() + "=" + requestNew.getUrl() + " " + requestNew.getMethod());
}
}