选项模式

此开源图书由ithaiq原创,创作不易转载请注明出处

选项模式是go自创的设计模式,其他语言没有这种模式,在各种开源库里面可以看见大量的实现踪迹。主要使用在大量参数初始化时的场景

package main

import (
	"time"
)

type Connection struct {
	addr    string
	cache   bool
	timeout time.Duration
}

const (
	defaultTimeout = 10
	defaultCaching = false
)

type options struct {
	timeout time.Duration
	caching bool
}

// Option overrides behavior of Connect.
//type Option interface {
//	apply(*options)
//}

type optionFunc func(*options)

//func (f optionFunc) apply(o *options) {
//	f(o)
//}

type optionFuncs []optionFunc

func (o optionFuncs) Apply(u *options) {
	for _, f := range o {
		f(u)
	}
}

func WithTimeout(t time.Duration) optionFunc {
	return optionFunc(func(o *options) {
		o.timeout = t
	})
}

func WithCaching(cache bool) optionFunc {
	return optionFunc(func(o *options) {
		o.caching = cache
	})
}

// Connect creates a connection.
func NewConnect(addr string, opts ...optionFunc) (*Connection, error) {
	options := options{
		timeout: defaultTimeout,
		caching: defaultCaching,
	}
	optionFuncs(opts).Apply(&options)
	return &Connection{
		addr:    addr,
		cache:   options.caching,
		timeout: options.timeout,
	}, nil
}

最后更新于

这有帮助吗?