Go中建造者模式通过结构体+链式方法+可选配置函数实现,将复杂对象构造与表示分离,支持分步定制;典型流程为定义Product、Builder、WithXxx方法和Build验证。
在 Go 语言中应用建造者模式,核心是**将对象的构造过程与表示分离,支持分步骤、可定制地创建复杂结构**。Go 没有构造函数重载或默认参数,也没有类继承体系,因此建造者模式常通过结构体 + 链式方法(返回指针)+ 可选配置函数来实现,既清晰又符合 Go 的简洁哲学。
先明确你要构建的复杂对象。它通常是字段较多、部分字段可选、存在约束或依赖关系的结构体。
type RequestConfig struct {
method string
url string
headers map[string]string
timeout time.Duration
retries int
body []byte
}建造者是一个独立结构体,持有目标对象的字段副本,并提供一系列“设置方法”。每个方法修改自身并返回 *Builder,实现链式调用。
type RequestConfigBuilder struct {
method string
url string
headers map[string]string
ti
meout time.Duration
retries int
body []byte
}
func NewRequestConfigBuilder() RequestConfigBuilder {
return &RequestConfigBuilder{
headers: make(map[string]string),
timeout: 30 time.Second,
retries: 3,
}
}
每个设置方法接收参数,更新对应字段,并返回 b *RequestConfigBuilder,支持连续调用。
mapcopy 或重新 make)func (b *RequestConfigBuilder) WithMethod(method string) *RequestConfigBuilder {
b.method = method
return b
}
func (b RequestConfigBuilder) WithURL(url string) RequestConfigBuilder {
b.url = url
return b
}
func (b RequestConfigBuilder) WithHeader(key, value string) RequestConfigBuilder {
if b.headers == nil {
b.headers = make(map[string]string)
}
b.headers[key] = value
return b
}
func (b RequestConfigBuilder) WithTimeout(d time.Duration) RequestConfigBuilder {
if d > 0 {
b.timeout = d
}
return b
}
Build() 是建造者的终点,负责:
func (b *RequestConfigBuilder) Build() (*RequestConfig, error) {
if b.url == "" {
return nil, fmt.Errorf("url is required")
}
if b.method == "" {
b.method = "GET"
}
// 深拷贝 headers 避免外部修改影响后续复用
safeHeaders := make(map[string]string)
for k, v := range b.headers {
safeHeaders[k] = v
}
return &RequestConfig{
method: b.method,
url: b.url,
headers: safeHeaders,
timeout: b.timeout,
retries: b.retries,
body: b.body,
}, nil}
cfg, err := NewRequestConfigBuilder().
WithURL("https://api.example.com/users").
WithMethod("POST").
WithHeader("Content-Type", "application/json").
WithTimeout(5 * time.Second).
Build()
if err != nil {
log.Fatal(err)
}