golang option模式

洞察源码,发现几乎都是使用option模式进行加载参数来实现的

1.先上代码

package main

import "fmt"

type Customer struct {
    id          int
    name    string
    gender  string
    phone   string
    age int8
}

type Option func(customer *Customer)

func WithId(id int) Option {
    return func(customer *Customer) {
        customer.id = id
    }
}

func WithGender(gender string) Option {
    return func(customer *Customer) {
        customer.gender = gender
    }
}

func WithName(name string) Option {
    return func(customer *Customer) {
        customer.name = name
    }
}

func WithPhone(phone string) Option {
    return func(customer *Customer) {
        customer.phone = phone
    }
}

func WithAge(age int8) Option {
    return func(customer *Customer) {
        customer.age = age
    }
}

func NewCustomer(options ...Option) Customer {
    customer := Customer{}
    for _, option := range options {
        // 用户自定义的初始化函数
        option(&customer)
    }
    return customer
}


func main() {
    customer := NewCustomer(WithAge(20),WithId(1), WithName("lazyr"), WithGender("man"), WithPhone("192993939393"))
    fmt.Println(customer)
}

总结:实际是闭包的应用,代码用得很巧妙

你可能感兴趣的:(golang option模式)