Skip to content

Instantly share code, notes, and snippets.

@kasari
Created February 5, 2018 22:41
Show Gist options
  • Save kasari/7d81bbca26e544bca7162d5307560b3d to your computer and use it in GitHub Desktop.
Save kasari/7d81bbca26e544bca7162d5307560b3d to your computer and use it in GitHub Desktop.
package main
import "fmt"
type Unit struct {
ID int
Name string
}
type Player struct {
unit *UnitLazy
}
func NewPlayer() *Player {
return &Player{
unit: NewUnitLazy(getUnit),
}
}
func (p *Player) Unit() *Unit {
return p.unit.Get()
}
func getUnit() *Unit {
fmt.Println("Get Unit")
return &Unit{1, "hoge"}
}
func main() {
p := NewPlayer()
unit := p.Unit()
fmt.Println(unit)
unit = p.Unit()
fmt.Println(unit)
}
type Lazy struct {
v interface{}
getter func() interface{}
}
func NewLazy(getter func() interface{}) *Lazy {
return &Lazy{
getter: getter,
}
}
func (l *Lazy) Get() interface{} {
if l.v != nil {
return l.v
}
v := l.getter()
l.v = v
return v
}
type UnitLazy struct {
*Lazy
}
func (ul *UnitLazy) Get() *Unit {
return ul.Lazy.Get().(*Unit)
}
func NewUnitLazy(getter func() *Unit) *UnitLazy {
return &UnitLazy{
NewLazy(func() interface{} {
return getter()
}),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment