go 依賴(lài)注入與控制反轉(zhuǎn)

簡(jiǎn)介依賴(lài)注入與控制反轉(zhuǎn)

控制反轉(zhuǎn)

正常情況下,對(duì)函數(shù)或方法的調(diào)用是調(diào)用方主動(dòng)直接的行為,調(diào)用方清楚的知道被調(diào)用的函數(shù)名、參數(shù)類(lèi)型,直接主動(dòng)調(diào)用;包括對(duì)象的初始化也是顯式的直接初始化;控制反轉(zhuǎn)就是將這種行為變成間接行為,主調(diào)方不是直接調(diào)用函數(shù)或?qū)ο?而是使用框架代碼間接的調(diào)用或初始化,這種行為成為"控制反轉(zhuǎn)",控制反轉(zhuǎn)可以解耦合調(diào)用方與被調(diào)用方,使用框架的程序常常由框架驅(qū)動(dòng)整個(gè)程序,在框架下寫(xiě)的業(yè)務(wù)代碼是被框架驅(qū)動(dòng)的,這種模式就是"控制反轉(zhuǎn)"

依賴(lài)注入

"依賴(lài)注入"是實(shí)現(xiàn)"控制反轉(zhuǎn)"的一種方法,如果說(shuō)"控制反轉(zhuǎn)"是一種設(shè)計(jì)思想,那"依賴(lài)注入"是就是這種思想的一種實(shí)現(xiàn),通過(guò)注入?yún)?shù)或?qū)嵗姆绞綄?shí)現(xiàn)控制反轉(zhuǎn)

inject 框架的依賴(lài)注入

inject 演練

1.對(duì)函數(shù)的注入調(diào)用

使用 map 實(shí)現(xiàn)一個(gè)字符串到函數(shù)的映射,map 中的 Value 類(lèi)型被寫(xiě)成 func(),不同的參數(shù)與返回值的類(lèi)型的函數(shù)不能通用,因此將 map 的 Value 定義為 interface{} 空接口類(lèi)型,使用類(lèi)型斷言與反射來(lái)實(shí)現(xiàn),

type s1 interface{}

func Format(name string, level s1) {
   fmt.Printf("name=%s,level=%s", name, level)
}

func main() {
  // 控制實(shí)例創(chuàng)建
   ijt := inject.New()
  
  // 實(shí)參注入
   ijt.Map("lucy")
   ijt.MapTo("t4", (*s1)(nil))
  
  // 函數(shù)反轉(zhuǎn)調(diào)用
   ijt.Invoke(Format)
}

/* 執(zhí)行輸出:
name=lucy,level=t4
Process finished with exit code 0
*/

inject 提供了一種注入?yún)?shù)調(diào)用函數(shù)的通用功能,inject 相當(dāng)于創(chuàng)建了一個(gè)控制實(shí)例,用來(lái)實(shí)現(xiàn)對(duì)函數(shù)的注入調(diào)用;

2.對(duì) struct 的注入調(diào)用

type S1 interface{}

type User struct {
   Name  string `inject`
   Level S1     `inject`
}

func main() {
   // 創(chuàng)建被注入的實(shí)例
   u := User{}
   
   // 創(chuàng)建控制實(shí)例
   ijt := inject.New()

   // 初始化注入值
   ijt.Map("lucy")
   ijt.MapTo("t4", (*S1)(nil))
   
   // 實(shí)現(xiàn)對(duì) struct 注入
   _ = ijt.Apply(&u)

   fmt.Printf("u=%v\n", u)
}
/* 執(zhí)行輸出:
u={lucy t4}
Process finished with exit code 0  
*/

inject 提供對(duì)結(jié)構(gòu)體類(lèi)型的通用注入方法

inject原理解析

入口函數(shù)New

injectNew() 函數(shù)構(gòu)建一個(gè)具體類(lèi)型的實(shí)例作為內(nèi)部注入引擎,返回一個(gè) Injector 類(lèi)型的接口,面向接口設(shè)計(jì)的思想,對(duì)外暴露接口方法隱藏內(nèi)部實(shí)現(xiàn):

func New() Injector {
   return &injector{
      values: make(map[reflect.Type]reflect.Value),
   }
}

接口設(shè)計(jì)

Injector 暴露所有方法給外部調(diào)用者,這些方法可歸為兩大類(lèi):

  • 第一類(lèi)對(duì)參數(shù)注入進(jìn)行初始化,將結(jié)構(gòu)類(lèi)型的字段的注入與函數(shù)的參數(shù)的注入統(tǒng)一一套方法實(shí)現(xiàn)
  • 第二類(lèi)專(zhuān)用注入實(shí)現(xiàn),分別是生成結(jié)構(gòu)對(duì)象與調(diào)用函數(shù)方法

inject 將多個(gè)接口組合為一個(gè)大接口,符合 go 的 Duck 類(lèi)型接口設(shè)計(jì)原則,Injector 接口如下:

// Injector represents an interface for mapping and injecting dependencies into structs
// and function arguments.
type Injector interface {
   // 抽象生成注入結(jié)構(gòu)實(shí)例的接口
   Applicator
  
   // 抽象函數(shù)調(diào)用接口
   Invoker
  
   // 抽象注入?yún)?shù)的接口
   TypeMapper
   // SetParent sets the parent of the injector. If the injector cannot find a
   // dependency in its Type map it will check its parent before returning an
   // error.
   // 實(shí)現(xiàn)一個(gè)注入實(shí)例鏈 下游能夠覆蓋上游的類(lèi)型
   SetParent(Injector)
}
TypeMapper

接口實(shí)現(xiàn)對(duì)注入?yún)?shù)操作的匯總,包括設(shè)置與查找相關(guān)參數(shù)的類(lèi)型、值的方法,函數(shù)的實(shí)參與結(jié)構(gòu)體的字段,在 inject 內(nèi)部放在 map[reflect.Type]reflect.Value 類(lèi)型的 map 中,代碼如下:

// TypeMapper represents an interface for mapping interface{} values based on type.
type TypeMapper interface {
   // 如下三個(gè)方法設(shè)置參數(shù)
   // Maps the interface{} value based on its immediate type from reflect.TypeOf.
   Map(interface{}) TypeMapper
   // Maps the interface{} value based on the pointer of an Interface provided.
   // This is really only useful for mapping a value as an interface, as interfaces
   // cannot at this time be referenced directly without a pointer.
   MapTo(interface{}, interface{}) TypeMapper
   // Provides a possibility to directly insert a mapping based on type and value.
   // This makes it possible to directly map type arguments not possible to instantiate
   // with reflect like unidirectional channels.
   Set(reflect.Type, reflect.Value) TypeMapper
  
   // 查找參數(shù)
   // Returns the Value that is mapped to the current type. Returns a zeroed Value if
   // the Type has not been mapped.
   Get(reflect.Type) reflect.Value
}
Invoker

Invoker 方法是調(diào)用被注入實(shí)參的函數(shù)

// Invoker represents an interface for calling functions via reflection.
type Invoker interface {
   // Invoke attempts to call the interface{} provided as a function,
   // providing dependencies for function arguments based on Type. Returns
   // a slice of reflect.Value representing the returned values of the function.
   // Returns an error if the injection fails.
   Invoke(interface{}) ([]reflect.Value, error)
}
Applicator

Applicator 接口中 Apply 方法實(shí)現(xiàn)對(duì)結(jié)構(gòu)體的注入

// Applicator represents an interface for mapping dependencies to a struct.
type Applicator interface {
   // Maps dependencies in the Type map to each field in the struct
   // that is tagged with 'inject'. Returns an error if the injection
   // fails.
   Apply(interface{}) error
}
inject 處理流程:
  1. 通過(guò) inject.New() 創(chuàng)建注入引擎,返回 Injector 接口類(lèi)型變量
  2. 調(diào)用 TypeMapper 接口(Injector 內(nèi)的 TypeMapper)的方法注入 struct 字段值或函數(shù)的是實(shí)參值
  3. 調(diào)用 Invoke 方法執(zhí)行被注入的函數(shù),或調(diào)用 Applicator 接口方法獲得被注入后的結(jié)構(gòu)實(shí)例

內(nèi)部實(shí)現(xiàn)

inject 內(nèi)部的注入引擎 injector 的實(shí)現(xiàn)

injector 對(duì) struct 注入實(shí)現(xiàn)
type injector struct {
   values map[reflect.Type]reflect.Value
   parent Injector
}

values 中存放的被注入 struct 的字段類(lèi)型與值或函數(shù)實(shí)參的類(lèi)型與值;values 是以 reflect.Type 為 Key 的 map ,如果一個(gè)結(jié)構(gòu)體的字段類(lèi)型相同,后注入大參數(shù)會(huì)覆蓋前面的參數(shù),規(guī)避的辦法是使用 MapTo 方法,通過(guò)抽象出一個(gè)接口類(lèi)型來(lái)避免覆蓋

func (i *injector) MapTo(val interface{}, ifacePtr interface{}) TypeMapper {
   i.values[InterfaceOf(ifacePtr)] = reflect.ValueOf(val)
   return i
}
injector 對(duì)函數(shù)注入實(shí)現(xiàn)
// Invoke attempts to call the interface{} provided as a function,
// providing dependencies for function arguments based on Type.
// Returns a slice of reflect.Value representing the returned values of the function.
// Returns an error if the injection fails.
// It panics if f is not a function
func (inj *injector) Invoke(f interface{}) ([]reflect.Value, error) {
   // 獲取函數(shù)類(lèi)型的 Type
   t := reflect.TypeOf(f)

   // 構(gòu)造一個(gè)存放函數(shù)實(shí)參 Value 值的數(shù)組
   var in = make([]reflect.Value, t.NumIn()) //Panic if t is not kind of Func
  
   // 使用反射獲取函數(shù)的實(shí)參 reflect.Type 逐個(gè)去 injector 中查找注入 Value 值
   for i := 0; i < t.NumIn(); i++ {
      argType := t.In(i)
      val := inj.Get(argType)
      if !val.IsValid() {
         return nil, fmt.Errorf("Value not found for type %v", argType)
      }

      in[i] = val
   }
   
   // 反射調(diào)用函數(shù)
   return reflect.ValueOf(f).Call(in), nil
}

facebook 的 inject

通過(guò)創(chuàng)建與連接各種對(duì)象來(lái)解耦組件之間的依賴(lài)關(guān)系,避免手動(dòng)配置每個(gè)組件的依賴(lài)關(guān)系

type RedisDB struct {
    Name string
    Adds string
}

type App struct {
    Name  string
    Redis *RedisDB `inject:""`
}

func (a *App) Create() string {
    return "create app in db name:" + a.Redis.Name + "[" + a.Redis.Adds + "]" + "app name:" + a.Name
}

type AppObject struct {
    App *App
}

func Init() *AppObject {
    db := RedisDB{
        Name: "redis",
        Adds: "192.168.1.1"}

    app := App{Name: "go-app"}

    var g inject.Graph

    _ = g.Provide(
        &inject.Object{Value: &app},
        &inject.Object{Value: &db},
    )
    _ = g.Populate()

    return &AppObject{
        App: &app,
    }

}

func main() {
    obj := Init()
    fmt.Println(obj.App.Create())
}
/*執(zhí)行輸出:
create app in db name:redis[192.168.1.1] app name :go-app

Process finished with exit code 0
*/

Populate 函數(shù)

// Populate is a short-hand for populating a graph with the given incomplete
// object values.
func Populate(values ...interface{}) error {
    var g Graph
    for _, v := range values {
        if err := g.Provide(&Object{Value: v}); err != nil {
            return err
        }
    }
    return g.Populate()
}

Populate方法使用給定的不完整對(duì)象值填補(bǔ)對(duì)象圖形,簡(jiǎn)單的手段填充

Graph 對(duì)象

// The Graph of Objects.
type Graph struct {
    Logger      Logger // Optional, will trigger debug logging.
    unnamed     []*Object
    unnamedType map[reflect.Type]bool
    named       map[string]*Object
}

Graph 包含以下方法:

  • Objects
  • Populate
  • Provide

Objects

對(duì)象返回所有已知對(duì)象,命名以及未命名

Populate

填充不完整的對(duì)象

Provide

向Graph提供對(duì)象

Logger 對(duì)象

type Logger interface {
    Debugf(format string, v ...interface{})
}

記錄簡(jiǎn)單的日志

Object 對(duì)象

// An Object in the Graph.
type Object struct {
    Value        interface{}
    Name         string             // Optional
    Complete     bool               // If true, the Value will be considered complete
    Fields       map[string]*Object // Populated with the field names that were injected and their corresponding *Object.
    reflectType  reflect.Type
    reflectValue reflect.Value
    private      bool // If true, the Value will not be used and will only be populated
    created      bool // If true, the Object was created by us
    embedded     bool // If true, the Object is an embedded struct provided internally
}

Graph 中的對(duì)象,每個(gè)注入對(duì)象對(duì)應(yīng) Object,通過(guò) Object 完成

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容