Skip to content

Instantly share code, notes, and snippets.

@sekky0905
Last active November 14, 2018 06:34
Show Gist options
  • Save sekky0905/baf392d462808192f85288a52b35e62f to your computer and use it in GitHub Desktop.
Save sekky0905/baf392d462808192f85288a52b35e62f to your computer and use it in GitHub Desktop.
Goの構造体のフィールドに関数を埋め込んでDIを実現してみる ref: https://qiita.com/Sekky0905/items/be5d83674a1aa78a397a
package main
import (
"fmt"
)
type Hoge struct {
}
func (h *Hoge) Foo(bar string) string {
return fmt.Sprintf("%sだ!", bar)
}
func main() {
h := &Hoge{}
fmt.Println(h.Foo("sekky0905"))
}
sekky0905だ!
// A struct with 6 fields.
struct {
x, y int
u float32
_ float32 // padding
A *[]int
F func()
}
import "fmt"
type Hoge struct {
Foo func(bar string) string
}
func main() {
f := func(bar string) string {
return fmt.Sprintf("%sだ!", bar)
}
h := &Hoge{Foo: f}
fmt.Println(h.Foo("sekky0905"))
}
sekky0905だ!
package main
import (
"fmt"
)
type Strategy interface {
ExecuteStrategy()
}
type StrategyA struct {
Name string
}
func (s *StrategyA) ExecuteStrategy() {
fmt.Printf("%s実行したぜ~!\n", s.Name)
}
func NewStrategyA(name string) Strategy {
return &StrategyA{
Name: name,
}
}
type StrategyB struct {
Name string
}
func (s *StrategyB) ExecuteStrategy() {
fmt.Printf("%s実行したよ~!\n", s.Name)
}
func NewStrategyB(name string) Strategy {
return &StrategyB{
Name: name,
}
}
type Player struct {
Strategy Strategy // Strategy型にすることで、後で埋め込む際にStrategy型を実装した任意の型を埋め込むことができる
}
func main() {
sa := NewStrategyA("StrategyA")
p1 := &Player{
Strategy: sa,
}
p1.Strategy.ExecuteStrategy()
sb := NewStrategyB("StrategyB")
p2 := &Player{
Strategy: sb,
}
p2.Strategy.ExecuteStrategy()
}
StrategyA実行したぜ~!
StrategyB実行したよ~!
package main
import (
"fmt"
)
type Player struct {
ExecuteStrategy func(name string)
}
func ExecuteStrategyA(name string) {
fmt.Printf("%s実行したぜ~!\n", name)
}
func ExecuteStrategyB(name string) {
fmt.Printf("%s実行したよ~!\n", name)
}
func main() {
p1 := &Player{
ExecuteStrategy: ExecuteStrategyA,
}
p1.ExecuteStrategy("StrategyA")
p2 := &Player{
ExecuteStrategy: ExecuteStrategyB,
}
p2.ExecuteStrategy("StrategyB")
}
StrategyA実行したぜ~!
StrategyB実行したよ~!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment