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)
}

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容