4. 建造者模式(Builder)
4. 建造者模式(Builder)
问题:对象有很多可选参数,构造函数参数列表越来越长。
核心:用链式调用一步步构建对象,最终 build() 出成品。
class HttpRequest {
constructor() {
this.method = 'GET';
this.url = '';
this.headers = {};
this.body = null;
}
}
class HttpRequestBuilder {
#req = new HttpRequest();
method(m) { this.#req.method = m; return this; }
url(u) { this.#req.url = u; return this; }
header(k, v) { this.#req.headers[k] = v; return this; }
body(b) { this.#req.body = b; return this; }
build() { return this.#req; }
}
const req = new HttpRequestBuilder()
.method('POST')
.url('/api/users')
.header('Content-Type', 'application/json')
.body({ name: 'Hok Keung' })
.build();package builder
type Request struct {
Method string
URL string
Headers map[string]string
Body any
}
type RequestBuilder struct {
req *Request
}
func NewRequestBuilder() *RequestBuilder {
return &RequestBuilder{req: &Request{
Method: "GET",
Headers: make(map[string]string),
}}
}
func (b *RequestBuilder) Method(m string) *RequestBuilder {
b.req.Method = m
return b
}
func (b *RequestBuilder) URL(u string) *RequestBuilder {
b.req.URL = u
return b
}
func (b *RequestBuilder) Header(k, v string) *RequestBuilder {
b.req.Headers[k] = v
return b
}
func (b *RequestBuilder) Body(body any) *RequestBuilder {
b.req.Body = body
return b
}
func (b *RequestBuilder) Build() *Request {
return b.req
}