golang option模式

2022-08-09  本文已影响0人  江江简书

洞察源码,发现几乎都是使用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)
}

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

上一篇下一篇

猜你喜欢

热点阅读