设计模式之高级配置模式
设计模式之高级配置模式
如果读者喜欢阅读出名的框架或者中间件的源码,会发现质量高的代码中,对于结构体的创建往往只需要传入相同的参数即可,非常的简洁直观。
1
func NewServer(opt ...ServerOption) // 摘抄于GRPC框架源码
下面来介绍一下这种创建方式—高级配置模式。
高级配置模式 Option Mode
结构体中需要通过外部传入参数来进行初始化的参数可以抽象成Options结构体
1
2
3
4
type ServerOptions struct {
Address string
Port int
}
我们要如何设置这个Options呢?这时重点就来了,我们的Option函数,配置函数发挥重要作用。
1
2
3
type ServerOption struct {
apply func(*ServerOptions)
}
通过直观的调用设置函数来得到对应的Option函数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func WithAddress(address string) ServerOption {
return ServerOption{
apply: func(opts *ServerOptions) {
opts.Address = address
},
}
}
func WithPort(port int) ServerOption {
return ServerOption{
apply: func(opts *ServerOptions) {
opts.Port = port
},
}
}
得到Option配置器后,就可以在结构体初始化的时候传入并进行应用了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func NewServer(opt ...ServerOption) *Server {
options := &ServerOptions{
Address: "default_address",
Port: 80, // 默认值
}
for _, o := range opt {
o.apply(options)
}
return &Server{
Options: options,
}
}
addoption := WithAddress("localhost")
portoption := WithPort(8080)
server := NewServer(addoption, portoption)
This post is licensed under CC BY 4.0 by the author.