平时用到的设计模式(一)|Go主题月

311 阅读1分钟

单例模式

package singleton

import "sync"

var (
    goInstance *Instance
    once       sync.Once
)

// 使用go 实现单例模式
func GoInstance(name string) *Instance {
    if goInstance == nil {
        once.Do(func() {
            goInstance = &Instance{
                Name: name,
            }
        })
    }
    return goInstance
}

使用 once.Do 来保证 某个对象只会初始化一次,有一点要要注意的是 这个 once.Do 只会被运行一次,哪怕 Do 函数里面的发生了异常,对象初始化失败了,这个 Do 函数也不会被再次执行了

// use a global client
var DefaultClient = New()

var New = func() *defaultClient {
   return &defaultClient{
      opts : &Options{
         protocol : "proto",
      },
   }
}

选项模式

// 选项参数
type ServerOptions struct {
   address string  // ( ip://127.0.0.1:8080、 dns://www.google.com)
   network string  // network type, tcp、udp
   protocol string  // protocol typpe, proto、json
}

type ServerOption func(*ServerOptions)

// 设置某一个属性的func
func WithAddress(address string) ServerOption{
   return func(o *ServerOptions) {
      o.address = address
   }
}

func WithNetwork(network string) ServerOption {
   return func(o *ServerOptions) {
      o.network = network
   }
}