简介
建造者模式应用场景是
- 类中的属性比较多
- 类中的属性之间有一定的依赖关系,或者是约束关系
- 存在必选和非必选的属性
- 希望创建不可变的对象
与工厂模式区别是建造者模式常用于创建参数比较多的对象时候。常见的做法是必填参数直接传递,可选参数通过传递可变的方法进行创建
package main
const (
defaultMaxTotal = 10
defaultMaxIdle = 9
defalutMinIdle = 1
)
type ResourcePoolConfig struct {
name string
maxTotal int
maxIdle int
minIdle int
}
type ResourcePoolConfigBuilder struct {
name string
maxTotal int
maxIdle int
minIdle int
}
func (b *ResourcePoolConfigBuilder) SetName(name string) error {
if name == "" {
return fmt.Errorf("name can not be empty")
}
b.name = name
return nil
}
func (b *ResourcePoolConfigBuilder) SetMinIdle(minIdle int) error {
if minIdle < 0 {
return fmt.Errorf("max tatal cannot < 0, input: %d", minIdle)
}
b.minIdle = minIdle
return nil
}
func (b *ResourcePoolConfigBuilder) SetMaxIdle(maxIdle int) error {
if maxIdle < 0 {
return fmt.Errorf("max tatal cannot < 0, input: %d", maxIdle)
}
b.maxIdle = maxIdle
return nil
}
func (b *ResourcePoolConfigBuilder) SetMaxTotal(maxTotal int) error {
if maxTotal < 0 {
return fmt.Errorf("max tatal cannot <=0, input: %d", maxTotal)
}
b.maxTotal = maxTotal
return nil
}
//Build Build
func (b *ResourcePoolConfigBuilder) Build() (*ResourcePoolConfig, error) {
if b.name == "" {
return nil, fmt.Errorf("name can not be empty")
}
//设置默认值
if b.minIdle == 0 {
b.minIdle = defalutMinIdle
}
if b.maxIdle == 0 {
b.maxIdle = defaultMaxIdle
}
if b.maxTotal == 0 {
b.maxTotal = defaultMaxTotal
}
if b.maxTotal < b.maxIdle {
return nil, fmt.Errorf("max total(%d) cannot < max idle(%d)", b.maxTotal, b.maxIdle)
}
if b.minIdle > b.maxIdle {
return nil, fmt.Errorf("max idle(%d) cannot < min idle(%d)", b.maxIdle, b.minIdle)
}
return &ResourcePoolConfig{
name: b.name,
maxTotal: b.maxTotal,
maxIdle: b.maxIdle,
minIdle: b.minIdle,
}, nil
}