建造者模式一种对象构建模式,是将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。构建的对象很大并且需要多个步骤时,使用构建器模式,有助于减小构造函数的大小。把一个整体的构造函数分解成各个属性的构造函数,并在各个构造函数上都加上审查。
假如需要创建一个DB连接池类
type DBPool struct {dsn stringmaxOpenConn intmaxIdleConn int...maxConnLifeTime time.Duration
}
假设有很多很多属性,那么构造函数会很大。使用建造者创建构造函数如下。
type DBPoolBuilder struct {DBPoolerr error
}func Builder () *DBPoolBuilder {b := new(DBPoolBuilder)// 设置 DBPool 属性的默认值b.DBPool.dsn = "127.0.0.1:3306"b.DBPool.maxConnLifeTime = 1 * time.Secondb.DBPool.maxOpenConn = 30return b
}func (b *DBPoolBuilder) DSN(dsn string) *DBPoolBuilder {if b.err != nil {return b}if dsn == "" {b.err = fmt.Errorf("invalid dsn, current is %s", dsn)}b.DBPool.dsn = dsnreturn b
}func (b *DBPoolBuilder) MaxOpenConn(connNum int) *DBPoolBuilder {if b.err != nil {return b}if connNum < 1 {b.err = fmt.Errorf("invalid MaxOpenConn, current is %d", connNum)}b.DBPool.maxOpenConn = connNumreturn b
}func (b *DBPoolBuilder) MaxConnLifeTime(lifeTime time.Duration) *DBPoolBuilder {if b.err != nil {return b}if lifeTime < 1 * time.Second {b.err = fmt.Errorf("connection max life time can not litte than 1 second, current is %v", lifeTime)}b.DBPool.maxConnLifeTime = lifeTimereturn b
}func (b *DBPoolBuilder) Build() (*DBPool, error) {if b.err != nil {return nil, b.err}if b.DBPool.maxOpenConn < b.DBPool.maxIdleConn {return nil, fmt.Errorf("max total(%d) cannot < max idle(%d)", b.DBPool.maxOpenConn, b.DBPool.maxIdleConn)}return &b.DBPool, nil
使用构建模式创造DBPool
类型的对象
package main import "xxx/dbpool"func main() {dbPool, err := dbpool.Builder().DSN("localhost:3306").MaxOpenConn(50).MaxConnLifeTime(0 * time.Second).Build()if err != nil {fmt.Println(err)}fmt.Println(dbPool)
}