构造函数
type Person { name string, age int64, country string, ...}func NewPerson(name string,age int64,country sting)*Person{ return &Person{ name: name,}
package mainimport ( "fmt")type options struct { a int64 b string c map[int]string}func NewOption(opt ...ServerOption) *options { r := new(options) for _, o := range opt { o(r) } return r}type ServerOption func(*options)func WriteA(s int64) ServerOption { return func(o *options) { o.a = s }}func WriteB(s string) ServerOption { return func(o *options) { o.b = s }}func WriteC(s map[int]string) ServerOption { return func(o *options) { o.c = s }}func main() { opt1 := WriteA(int64(1)) opt2 := WriteB("test") opt3 := WriteC(make(map[int]string,0)) op := NewOption(opt1, opt2, opt3) fmt.Println(op.a, op.b, op.c)}
func NewServer(addr string, options ...func(*Server)) (*Server, error) { srv := &Server{ Addr: addr, } for _, option := range options { option(srv) } return srv} func timeout(d time.Duration) func(*Server) { return func(srv *Server) { srv.timeout = d }} func tls(c *config) func(*Server) { return func(srv *Server) { Tls := loadConfig(c) srv.tls = Tls }} //使用src, err = NewServer("localhost:8080", timeout(1), tls(path/to/cert))
类工厂模式
// 存放对应关系var mux map[string]func(option *Option) error // 注册handlerfunc register(key string, f func(option *Option) error) { if mux == nil { mux = make(map[string]func(option *Option) error) } if _, exist := mux[key]; exist { return errors.New("handler exist") } mux[key] = f} // factoryfunc factory(option *Option) error { return mux[option.Key](option)}
posted on 2018-09-13 10:39 阅读( ...) 评论( ...)