go-选项卡模式

发布时间 2023-06-29 23:03:39作者: 前方、有光
package main

import "fmt"

const (
    defaultName string = "张建平"
    defaultAge  int    = 27
    defaultHigh int    = 175
)

type User struct {
    Name string
    Age  int
    High int
}

type UserOptions struct {
    Name string
    Age  int
    High int
}

type UserOption interface {
    apply(*UserOptions)
}

type FuncUserOption struct {
    f func(*UserOptions)
}

func (fo FuncUserOption) apply(option *UserOptions) {
    fo.f(option)
}

func WithName(name string) UserOption {
    return FuncUserOption{
        f: func(options *UserOptions) {
            options.Name = name
        },
    }
}

func WithAge(age int) UserOption {
    return FuncUserOption{
        f: func(options *UserOptions) {
            options.Age = age
        },
    }
}

func WithHigh(high int) UserOption {
    return FuncUserOption{f: func(options *UserOptions) {
        options.High = high
    }}
}

func NewUser(opts ...UserOption) *User {
    options := UserOptions{
        Name: defaultName,
        Age:  defaultAge,
        High: defaultHigh,
    }
    for _, opt := range opts {
        opt.apply(&options)
    }
    return &User{
        Name: options.Name,
        Age:  options.Age,
        High: options.High,
    }
}

func main() {
    u1 := NewUser()
    fmt.Println(u1)
    u2 := NewUser(WithName("胖虎"))
    fmt.Println(u2)
    u3 := NewUser(WithName(""), WithAge(3))
    fmt.Println(u3)
}