gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/option/option.go (about) 1 package option 2 3 // Option 接口用于配置一个对象的属性 4 type Option[T, O any] interface { 5 Apply(target T) O 6 } 7 8 type ( 9 AnyOption Option[any, any] 10 CustomOption[T any] Option[T, any] 11 ProviderOption[O any] Option[any, O] 12 ) 13 14 // OptionFunc 使用配置函数配置一个对象的属性,此函数类型实现了 Option 接口 15 type Func[T, O any] func(target T) O 16 type AnyFunc Func[any, any] 17 18 func (f Func[T, O]) Apply(target T) O { 19 return f(target) 20 } 21 22 // Custom 与 Func 类似,但是没有返回值 23 type Custom[T any] func(target T) 24 type AnyCustom = Custom[any] 25 26 func (f Custom[T]) Apply(target T) any { 27 f(target) 28 return nil 29 } 30 31 type CustomFunc[T, O any] func(target T) 32 33 func (f CustomFunc[T, O]) Apply(target T) (o O) { 34 f(target) 35 return 36 } 37 38 // Provider 通过函数提供一个配置属性用于配置对象 39 type Provider[O any] func() O 40 type AnyProvider = Provider[any] 41 42 func (p Provider[O]) Apply(target any) O { 43 return p() 44 } 45 46 type ProviderFunc[T, O any] func() O 47 48 func (p ProviderFunc[T, O]) Apply(target any) O { 49 return p() 50 } 51 52 func Apply[T any](target T, options ...Option[T, any]) { 53 for _, option := range options { 54 option.Apply(target) 55 } 56 }