go ioc初探

在这里插入图片描述

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 控制反转,将对象创建的过程交由框架处理。
该版本未处理依赖等问题。


版权声明:本文为dawnto原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。