Golang - Option模式(1)(函数选项模式)

函数式选项模式(Functional Options Pattern)

Option模式的专业术语为:Functional Options Pattern(函数式选项模式)
Option模式为golang的开发者提供了将一个函数的参数设置为可选的功能,也就是说可以选择参数中的某几个,并且可以按任意顺序传入参数。
比如针对特殊场景需要不同参数的情况,C++可以直接用重载来写出任意个同名函数,在任意场景调用的时候使用同一个函数名即可;但同样情况下,在golang中我们就必须在不同的场景使用不同的函数,并且参数传递方式可能不同的人写出来是不同的样子,这将导致代码可读性差,维护性差。

优缺点

优点

1、支持传递多个参数,并且在参数个数、类型发生变化时保持兼容性
2、任意顺序传递参数
3、支持默认值
4、方便拓展

缺点

1、增加许多function,成本增大
2、参数不太复杂时,尽量少用

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import "fmt"
type Message struct {
   id      int
   name    string
   address string
   phone   int
}
func (msg Message) String() {
   fmt.Printf("ID:%d \n- Name:%s \n- Address:%s \n- phone:%d\n", msg.id, msg.name, msg.address, msg.phone)
}
func New(id, phone int, name, addr string) Message {
   return Message{
      id:      id,
      name:    name,
      address: addr,
      phone:   phone,
   }
}
type Option func(msg *Message)
var DEFAULT_MESSAGE = Message{id: -1, name: "-1", address: "-1", phone: -1}
func WithID(id int) Option {
   return func(m *Message) {
      m.id = id
   }
}
func WithName(name string) Option {
   return func(m *Message) {
      m.name = name
   }
}
func WithAddress(addr string) Option {
   return func(m *Message) {
      m.address = addr
   }
}
func WithPhone(phone int) Option {
   return func(m *Message) {
      m.phone = phone
   }
}
func NewByOption(opts ...Option) Message {
   msg := DEFAULT_MESSAGE
   for _, o := range opts {
      o(&msg)
   }
   return msg
}
func NewByOptionWithoutID(id int, opts ...Option) Message {
   msg := DEFAULT_MESSAGE
   msg.id = id
   for _, o := range opts {
      o(&msg)
   }
   return msg
}
func main() {
   message1 := New(1, 123, "message1", "cache1")
   message1.String()
   message2 := NewByOption(WithID(2), WithName("message2"), WithAddress("cache2"), WithPhone(456))
   message2.String()
   message3 := NewByOptionWithoutID(3, WithAddress("cache3"), WithPhone(789), WithName("message3"))
   message3.String()
}

posted @   李若盛开  阅读(96)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示