package main
import (
"fmt"
"reflect"
"sync"
)
var beanMap map[reflect.Type]reflect.Value
var lock sync.RWMutex
func init() {
beanMap = make(map[reflect.Type]reflect.Value)
lock = sync.RWMutex{}
}
func Set(beans ...any) {
lock.Lock()
defer lock.Unlock()
for i := range beans {
_type := reflect.TypeOf(beans[i])
if _type.Kind() != reflect.Ptr || _type.Elem().Kind() != reflect.Struct {
panic("it is not struct pointer")
}
if _, ok := beanMap[reflect.ValueOf(beans[i]).Type()]; !ok {
beanMap[reflect.ValueOf(beans[i]).Type()] = reflect.ValueOf(beans[i])
}
}
}
func Get[T any](bean T) T {
lock.RLock()
defer lock.RUnlock()
_type := reflect.TypeOf(bean)
if _type.Kind() != reflect.Ptr || _type.Elem().Kind() != reflect.Struct {
return bean
}
if v, ok := beanMap[reflect.TypeOf(bean)]; ok {
return v.Interface().(T)
}
return bean
}
type A struct {
Name string
}
type B struct {
Name string
}
type C struct {
Name string
}
func main() {
Set(&A{"A 你好呀"}, &B{"B--->"})
fmt.Println(Get((*A)(nil)))
fmt.Println(Get((*B)(nil)))
fmt.Println(Get((*C)(nil)))
}
Inversion Of Control 控制反转,将对象创建的过程交由框架处理。
该版本未处理依赖等问题。