golang构造函数
http://blog.jobbole.com/107442/?utm_source=blog.jobbole.com&utm_medium=relatedPostshttps://gocn.vip/question/1420
构造函数
type Person {
name string,
age int64,
country string,
...
}
func NewPerson(name string,age int64,country sting)*Person{
return &Person{ name: name,
}
package main
import (
"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))
类工厂模式
// 存放 <cond, handler> 对应关系
var mux map[string]func(option *Option) error
// 注册handler
func 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
}
// factory
func factory(option *Option) error {
return mux[option.Key](option)
}
posted on
2018-09-13 10:39
北京涛子 阅读(
...) 评论(
)
编辑
收藏
转载于:https://www.cnblogs.com/liujitao79/p/9639100.html