【golang】设计模式-选项设计模式

342 阅读1分钟

选项设计模式

很多开源项目中都使用到选项设计模式。适合参数非常多,影响调用方使用时,使用选项模式,在增加或减少一个配置参数时很方便,只需增加或减少一个选项函数即可。为了实现选项的功能,我们增加了很多的代码,实现成本相对还是较高的。

两种实现方式

  1. 使用闭包实现
  2. 使用接口实现

闭包实现

package main

import "fmt"

type Options struct {
    StrOptions1 string
    StrOptions2 string
    StrOptions3 string
    IntOptions1 int
    IntOptions2 int
    IntOptions3 int
}

type OptionFunc func(opts *Options)

func InitOptions(optFs ...OptionFunc) *Options {
    options := &Options{}
    for _, optF := range optFs {
        optF(options)
    }
    return options
}

func WithStrOptions1(str string) OptionFunc {
    return func(opts *Options) {
        opts.StrOptions1 = str
    }
}

func WithStrOptions2(str string) OptionFunc {
    return func(opts *Options) {
        opts.StrOptions2 = str
    }
}

func WithStrOptions3(str string) OptionFunc {
    return func(opts *Options) {
        opts.StrOptions3 = str
    }
}

func main() {
    Opt := InitOptions(
        WithStrOptions1("str1"),
        WithStrOptions2("str2"),
        WithStrOptions3("Str3"))
    fmt.Printf("Options:%#v", Opt)
}
复制代码

接口实现

type options struct {
    cache  bool
    logger *zap.Logger
}

type Option interface {
    apply(*options)
}

type cacheOption bool

func (c cacheOption) apply(opts *options) {
    opts.cache = bool(c)
}

func WithCache(c bool) Option {
    return cacheOption(c)
}

type loggerOption struct {
    Log *zap.Logger
}

func (l loggerOption) apply(opts *options) {
    opts.logger = l.Log
}

func WithLogger(log *zap.Logger) Option {
    return loggerOption{Log: log}
}

func Open(addr string,opts ...Option) (*Connection, error){
    options := options{
        cache:  defaultCache,
        logger: zap.NewNop(),
    }

    for _, o := range opts {
        o.apply(&options)
    }

    // ...
}