当前位置:网站首页>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)))
}
边栏推荐
猜你喜欢
选择致敬持续奋斗背后的精神——对话威尔价值观【第四期】
MySQL之函数
上门预约服务类的App功能详解
Redis high availability - master-slave replication, sentinel mode, cluster
Problem solving win10 quickly open ipynb file
教你在HbuilderX上使用模拟器运行uni-app,良心教学!!!
【NOI模拟赛】Anaid 的树(莫比乌斯反演,指数型生成函数,埃氏筛,虚树)
N1 # if you work on a metauniverse product [metauniverse · interdisciplinary] Season 2 S2
云呐|公司固定资产管理系统有哪些?
提升工作效率工具:SQL批量生成工具思想
随机推荐
LeetCode 6006. Take out the least number of magic beans
7.5 simulation summary
LeetCode 8. String conversion integer (ATOI)
QT QPushButton details
从底层结构开始学习FPGA----FIFO IP核及其关键参数介绍
Upgrade openssl-1.1.1p for openssl-1.0.2k
Chapter 16 oauth2authorizationrequestredirectwebfilter source code analysis
QT -- thread
Teach you to run uni app with simulator on hbuilderx, conscience teaching!!!
数据库遇到的问题
用列錶初始化你的vector&&initializer_list簡介
MySQL global lock and table lock
Senparc. Weixin. Sample. MP source code analysis
【DesignMode】适配器模式(adapter pattern)
2022.7.5-----leetcode.729
【luogu CF487E】Tourists(圆方树)(树链剖分)(线段树)
XML配置文件(DTD详细讲解)
VBA fast switching sheet
Detailed explanation of APP functions of door-to-door appointment service
Transport layer protocol ----- UDP protocol