2020-04-25 22:22:45 +00:00
|
|
|
package defaulting
|
|
|
|
|
|
|
|
import (
|
|
|
|
"reflect"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Defaulter func(instance interface{})
|
|
|
|
|
|
|
|
type Registry interface {
|
|
|
|
Register(t reflect.Type, defaulter ...Defaulter)
|
|
|
|
Apply(instance interface{})
|
|
|
|
}
|
|
|
|
|
|
|
|
func New() Registry {
|
|
|
|
return ®istry{
|
|
|
|
defaulters: make(map[reflect.Type][]Defaulter),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type registry struct {
|
|
|
|
defaulters map[reflect.Type][]Defaulter
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *registry) Register(t reflect.Type, defaulter ...Defaulter) {
|
|
|
|
var given []Defaulter
|
|
|
|
if r, ok := r.defaulters[t]; ok {
|
|
|
|
given = r
|
|
|
|
}
|
|
|
|
|
2020-12-26 13:11:49 +00:00
|
|
|
given = append(given, defaulter...)
|
2020-04-25 22:22:45 +00:00
|
|
|
|
|
|
|
r.defaulters[t] = given
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *registry) Apply(instance interface{}) {
|
|
|
|
if defs, ok := r.defaulters[reflect.TypeOf(instance)]; ok {
|
|
|
|
for _, def := range defs {
|
|
|
|
def(instance)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|