golang之设计模式

[选项模式]

package main

import "fmt"

type OptionFunc func(*DoSomethingOption)

type DoSomethingOption struct {
    a int
    b string
    c bool
}

func NewDoSomethingOption(c bool, opts ...OptionFunc) *DoSomethingOption {
    s := &DoSomethingOption{c: c}
    for _, opt := range opts {
        opt(s)
    }
    return s
}

func WithA(a int) OptionFunc {
    return func(s *DoSomethingOption) {
        s.a = a
    }
}

func WithB(b string) OptionFunc {
    return func(s *DoSomethingOption) {
        s.b = b
    }
}

// 选项模式
func option() {
    s := NewDoSomethingOption(false, WithA(100), WithB("200"))
    fmt.Printf("选项模式数据:%+v \n", s)
}

 

 

更多设计模式

 

posted @ 2024-02-06 17:44  X-Wolf  阅读(2)  评论(0编辑  收藏  举报