当前位置:网站首页>Go learning - dependency injection

Go learning - dependency injection

2022-07-06 00:15:00 Duck boss

One 、 Dependency injection

package main

import "fmt"

func a1()  {
	fmt.Println("a1 call ")
}
func a2()  {
	fmt.Println("a2 call ")
}
func main() {
	// adopt map Implement dependency injection 
	myMap := make(map[string]func())
	myMap["a1"] = a1
	myMap["a2"] = a2
	// adopt map Of key Call function 
	myMap["a1"]()
	myMap["a2"]()
}

Two 、 Dependency injection framework

Download third party packages

3、 ... and 、 Use  inject Call function

package main

import (
	"fmt"
	"github.com/codegangsta/inject"
)

type S1 interface {}
type S2 interface {}

func Format(name string,company S1,level S2,age int)  {
	fmt.Printf("name = %s,company = %s,level = %s,age = %d!\n",name,company,level,age)
}
func main() {
   // Create a control instance 
	injector := inject.New()
	// Parameter injection 
	injector.Map("tom")
	injector.MapTo("tencent",(*S1)(nil))
	injector.MapTo("T4",(*S2)(nil))
	injector.Map(12)
	// Reverse call function 
	injector.Invoke(Format)
}

  Four 、inject Operating structure

package main

import (
	"fmt"
	"github.com/codegangsta/inject"
)

type S1 interface {}
type S2 interface {}
type Staff struct {
	Name string `inject`
	Company S1 `inject`
	Level S2 `inject`
	Age int `inject`
}

func main() {
	staff := Staff{}
	// Create a control instance 
	injector := inject.New()
	// Parameter injection 
	injector.Map("tom")
	injector.MapTo("tencent",(*S1)(nil))
	injector.MapTo("T4",(*S2)(nil))
	injector.Map(12)
	// Reverse call function 
	injector.Apply(&staff)
	fmt.Println(staff)
}

  5、 ... and 、 Grab information

package main

import (
	"fmt"
	"github.com/codegangsta/inject"
)

type S1 interface {}

func main() {
	fmt.Println(inject.InterfaceOf((*interface{})(nil)))
	fmt.Println(inject.InterfaceOf((*S1)(nil)))
}

 

原网站

版权声明
本文为[Duck boss]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140235517072.html