设计模式
约 140 字小于 1 分钟
2024-11-02
函数选项模式
type DBOptions struct {
Host string
Port int
}
type Option func(*DBOptions)
func WithHost(host string) Option {
return func(o *DBOptions) {
o.Host = host
}
}
func WithPort(port int) Option {
return func(o *DBOptions) {
o.Port = port
}
}
func NewDBOptions(opts ...Option) *DBOptions {
o := &DBOptions{Host: "127.0.0.1", Port: 2206}
for _, opt := range opts {
opt(o)
}
return o
}
func main() {
o := NewDBOptions(WithHost("10.0.0.1"))
}
单例模式
// 自己实现
var dbPool *DBOptions
var lock sync.Mutex
var initialed int32
func GetDbBPool() *DBOptions {
if atomic.LoadInt32(&initialed) == 1 {
return dbPool
}
lock.Lock()
defer lock.Unlock()
if initialed == 0 {
defer atomic.StoreInt32(&initialed, 1)
dbPool = NewDBOptions()
}
return dbPool
}
// 使用sync.Once
var once sync.Once
func GetDbBPool() *DBOptions {
once.Do(func() {
dbPool = NewDBOptions()
})
return dbPool
}