go options 模式

...

函数式选项模式的使用场景有哪些呢:我们一般用来配置一些基础的服务配置,比如MySQL,Redis,Kafka的配置,很多可选参数,可以方便动态灵活的配置想要配置的参数。

https://zhuanlan.zhihu.com/p/436468481

type Option func(*User)

func WithAge(age int) Option {
    return func(u *User) {
        u.Age = age
    }
}

func WithEmail(email string) Option {
    return func(u *User) {
        u.Email = email
    }
}

func WithPhone(phone string) Option {
    return func(u *User) {
        u.Phone = phone
    }
}

func WithGender(gender string) Option {
    return func(u *User) {
        u.Gender = gender
    }
}

func NewUser(id string, name string, options ...func(*User)) (*User, error) {
    user := User{
        ID:     id,
        Name:   name,
        Age:    0,
        Email:  "",
        Phone:  "",
        Gender: "female",
    }
    for _, option := range options {
        option(&user)
    }
    //...
    return &user, nil
}

user1, err := NewUser("1", "ada")
user2, err := NewUser("2", "bob", WithPhone("123456"), WithGender("male"))

 ...2

 1 package main
 2 
 3 import "fmt"
 4 
 5 type Customer struct {
 6     id          int
 7     name    string
 8     gender  string
 9     phone   string
10     age int8
11 }
12 
13 type Option func(customer *Customer)
14 
15 func WithId(id int) Option {
16     return func(customer *Customer) {
17         customer.id = id
18     }
19 }
20 
21 func WithGender(gender string) Option {
22     return func(customer *Customer) {
23         customer.gender = gender
24     }
25 }
26 
27 func WithName(name string) Option {
28     return func(customer *Customer) {
29         customer.name = name
30     }
31 }
32 
33 func WithPhone(phone string) Option {
34     return func(customer *Customer) {
35         customer.phone = phone
36     }
37 }
38 
39 func WithAge(age int8) Option {
40     return func(customer *Customer) {
41         customer.age = age
42     }
43 }
44 
45 func NewCustomer(options ...Option) Customer {
46     customer := Customer{}
47     for _, option := range options {
48         // 用户自定义的初始化函数
49         option(&customer)
50     }
51     return customer
52 }
53 
54 
55 func main() {
56     customer := NewCustomer(WithAge(20),WithId(1), WithName("lazyr"), WithGender("man"), WithPhone("192993939393"))
57     fmt.Println(customer)
58 }

 

posted @ 2023-03-01 10:23  voh99800  阅读(52)  评论(0编辑  收藏  举报