go-選項卡模式

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章