依存性注入(DI : Dependency Injection)は他の言語でもありますが、Goの場合にはより構造が単純化されると思います。
以下のコードは、
https://qiita.com/lostfind/items/cae2bca46d903bea167c
からですが、DIを使わないと電球の種類が変わる都度、部屋の工事が必要になるのですが、DI使って部屋にはソケットだけ用意して電球の種類はmain()ルーチンで簡単に変えられるようにしています。DIのメリットは変更発生時の変更範囲が分離されることと、テストが容易(関連するモジュールがなくてもできる)あたりがメリットになるでしょう。プログラムのライフサイクルで保守が大きな比重を占める訳なので、変更に強いコードと言えます。反面コードはその分冗長になります。
package main
import (
	"fmt"
)
func main() {
    lightOne := new(Incandescent) 	// only change these lines if new lighting is introduced
    lightTwo := new(LedLight)		//
    myRoom := NewRoom(lightOne, lightTwo) // DI or object Injection
    myRoom.SwitchOnOne()
    myRoom.SwitchOnTwo()
}
type LightSocket interface {
    LightUp() string
}
// room has two sokets
type Room struct {
    LightOne LightSocket		// prepare only socket, not bulb
    LightTwo LightSocket
}
// define switch on method of the two sockets
func (r *Room) SwitchOnOne() {
    fmt.Println("1番照明:", r.LightOne.LightUp())
}
func (r *Room) SwitchOnTwo() {
    fmt.Println("2番照明:", r.LightTwo.LightUp())
}
// Constructor Injection
func NewRoom(lightOne, lightTwo LightSocket) *Room {
    room := &Room{
        LightOne: lightOne,
        LightTwo: lightTwo,
    }
    return room
}
// Led light
type LedLight struct{}
func (*LedLight) LightUp() string {
    return "LEDが光るよ!"
}
// Filament bulb
type Incandescent struct{}
func (*Incandescent) LightUp() string {
    return "フィラメントが光るよ!"
}DIはデザインパターンそのものです。
admin
