设计模式——从 okhttp3 源码学习 builder 模式

废话少说,直接上代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.tracenote.bean.vo;

public class EvilPhone {
private String logo;
private Integer cost;
private String comment;

public EvilPhone(EvilPhone.Builder builder) {
this.logo = builder.logo;
this.cost = builder.cost;
this.comment = builder.comment;
}

public static class Builder {
String logo;
Integer cost;
String comment;

public EvilPhone.Builder logo(String logo) {
this.logo = logo;
return this;
}

public EvilPhone.Builder cost(Integer cost) {
this.cost = cost;
return this;
}

public EvilPhone.Builder comment(String comment) {
this.comment = comment;
return this;
}

public EvilPhone build() {
return new EvilPhone(this);
}
}

@Override
public String toString() {
return "EvilPhone{" +
"logo='" + logo + '\'' +
", cost=" + cost +
", comment='" + comment + '\'' +
'}';
}

public static void main(String[] args) {
EvilPhone evilPhone = new Builder()
.logo("flower")
.cost(996)
.comment("slave")
.build();
System.out.println(evilPhone.toString());
}
}

输出:

EvilPhone{logo=’flower’, cost=996, comment=’slave’}

对Builer模式使用方法的总结:

  1. 外部类的构造函数私有,且参数为静态内部类;
  2. 静态内部类拥有外部类相同的属;
  3. 为每一个属性,写一个方法,返回的是Builer;
  4. 最后一个方法是build方法,用于构建一个外部类;

附录,okhttp3 使用示例和 builder 模式源码:

1
2
3
4
Request request = new Request.Builder()
.url(url)
.get()//默认就是GET请求,可以不写
.build();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package okhttp3;

import java.net.URL;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import okhttp3.internal.Util;
import okhttp3.internal.http.HttpMethod;

public final class Request {
final HttpUrl url;
final String method;
final Headers headers;
@Nullable
final RequestBody body;
final Map<Class<?>, Object> tags;
@Nullable
private volatile CacheControl cacheControl;

Request(Request.Builder builder) {
this.url = builder.url;
this.method = builder.method;
this.headers = builder.headers.build();
this.body = builder.body;
this.tags = Util.immutableMap(builder.tags);
}

public HttpUrl url() {
return this.url;
}

public String method() {
return this.method;
}

public Headers headers() {
return this.headers;
}

@Nullable
public String header(String name) {
return this.headers.get(name);
}

public List<String> headers(String name) {
return this.headers.values(name);
}

@Nullable
public RequestBody body() {
return this.body;
}

@Nullable
public Object tag() {
return this.tag(Object.class);
}

@Nullable
public <T> T tag(Class<? extends T> type) {
return type.cast(this.tags.get(type));
}

public Request.Builder newBuilder() {
return new Request.Builder(this);
}

public CacheControl cacheControl() {
CacheControl result = this.cacheControl;
return result != null ? result : (this.cacheControl = CacheControl.parse(this.headers));
}

public boolean isHttps() {
return this.url.isHttps();
}

public String toString() {
return "Request{method=" + this.method + ", url=" + this.url + ", tags=" + this.tags + '}';
}

public static class Builder {
@Nullable
HttpUrl url;
String method;
okhttp3.Headers.Builder headers;
@Nullable
RequestBody body;
Map<Class<?>, Object> tags = Collections.emptyMap();

public Builder() {
this.method = "GET";
this.headers = new okhttp3.Headers.Builder();
}

Builder(Request request) {
this.url = request.url;
this.method = request.method;
this.body = request.body;
this.tags = (Map)(request.tags.isEmpty() ? Collections.emptyMap() : new LinkedHashMap(request.tags));
this.headers = request.headers.newBuilder();
}

public Request.Builder url(HttpUrl url) {
if (url == null) {
throw new NullPointerException("url == null");
} else {
this.url = url;
return this;
}
}

public Request.Builder url(String url) {
if (url == null) {
throw new NullPointerException("url == null");
} else {
if (url.regionMatches(true, 0, "ws:", 0, 3)) {
url = "http:" + url.substring(3);
} else if (url.regionMatches(true, 0, "wss:", 0, 4)) {
url = "https:" + url.substring(4);
}

return this.url(HttpUrl.get(url));
}
}

public Request.Builder url(URL url) {
if (url == null) {
throw new NullPointerException("url == null");
} else {
return this.url(HttpUrl.get(url.toString()));
}
}

public Request.Builder header(String name, String value) {
this.headers.set(name, value);
return this;
}

public Request.Builder addHeader(String name, String value) {
this.headers.add(name, value);
return this;
}

public Request.Builder removeHeader(String name) {
this.headers.removeAll(name);
return this;
}

public Request.Builder headers(Headers headers) {
this.headers = headers.newBuilder();
return this;
}

public Request.Builder cacheControl(CacheControl cacheControl) {
String value = cacheControl.toString();
return value.isEmpty() ? this.removeHeader("Cache-Control") : this.header("Cache-Control", value);
}

public Request.Builder get() {
return this.method("GET", (RequestBody)null);
}

public Request.Builder head() {
return this.method("HEAD", (RequestBody)null);
}

public Request.Builder post(RequestBody body) {
return this.method("POST", body);
}

public Request.Builder delete(@Nullable RequestBody body) {
return this.method("DELETE", body);
}

public Request.Builder delete() {
return this.delete(Util.EMPTY_REQUEST);
}

public Request.Builder put(RequestBody body) {
return this.method("PUT", body);
}

public Request.Builder patch(RequestBody body) {
return this.method("PATCH", body);
}

public Request.Builder method(String method, @Nullable RequestBody body) {
if (method == null) {
throw new NullPointerException("method == null");
} else if (method.length() == 0) {
throw new IllegalArgumentException("method.length() == 0");
} else if (body != null && !HttpMethod.permitsRequestBody(method)) {
throw new IllegalArgumentException("method " + method + " must not have a request body.");
} else if (body == null && HttpMethod.requiresRequestBody(method)) {
throw new IllegalArgumentException("method " + method + " must have a request body.");
} else {
this.method = method;
this.body = body;
return this;
}
}

public Request.Builder tag(@Nullable Object tag) {
return this.tag(Object.class, tag);
}

public <T> Request.Builder tag(Class<? super T> type, @Nullable T tag) {
if (type == null) {
throw new NullPointerException("type == null");
} else {
if (tag == null) {
this.tags.remove(type);
} else {
if (this.tags.isEmpty()) {
this.tags = new LinkedHashMap();
}

this.tags.put(type, type.cast(tag));
}

return this;
}
}

public Request build() {
if (this.url == null) {
throw new IllegalStateException("url == null");
} else {
return new Request(this);
}
}
}
}