build模式和options模式
package main
import "fmt"
// Server 初始化可选参数的
type Server struct {
url string
port string
protocol string
option string
}
//定义函数类型
type ModOption func(option *Server)
//将函数类型传入,然后再内部调用
func New(url string, port string, modOptions ...ModOption) *Server {
server := Server{
url: url,
port: port,
protocol: "TCP",
option: "默认参数",
}
for _, option := range modOptions {
option(&server)
}
return &server
}
func WithProtocol(protocol string) ModOption {
return func(server *Server) {
server.protocol = protocol
}
}
func WithOption(option string) ModOption {
return func(server *Server) {
server.option = option
}
}
//build模式,链式调用初始化
func Build(url string, port string) *Server {
server := Server{
url: url,
port: port,
protocol: "TCP",
option: "默认参数",
}
return &server
}
func (s *Server) buildProtocol(p string) *Server {
s.protocol = p
return s
}
func (s *Server) buildOption(p string) *Server {
s.option = p
return s
}
func main() {
var server1 = New("8.125.3.243", "2203", WithOption("可选参数2"))
fmt.Println(server1)
var server2 = Build("8.125.3.243", "2203").buildProtocol("111").buildOption("可选111")
fmt.Println(server2)
}
标签:protocol,string,模式,Server,build,func,Go,server,option
From: https://www.cnblogs.com/yinbit/p/17439675.html