Skip to content

Instantly share code, notes, and snippets.

@nasust nasust/flyweight.go
Created Dec 4, 2016

Embed
What would you like to do?
golang デザインパターン Flyweight
package main
import "fmt"
type Stamp struct {
stype string
}
func NewStamp(stype string) *Stamp {
return &Stamp{stype}
}
func (self *Stamp) Print() {
fmt.Print(self.stype)
}
type StampFactory struct {
pool map[string]*Stamp
}
func NewStampFactory() *StampFactory {
return &StampFactory{make(map[string]*Stamp)}
}
func (self *StampFactory) Get(stype string) *Stamp {
stamp, ok := self.pool[stype]
if !ok {
stamp = NewStamp(stype)
self.pool[stype] = stamp
}
return stamp
}
func main() {
factory := NewStampFactory()
stamps := []*Stamp{
factory.Get(""),
factory.Get(""),
factory.Get(""),
factory.Get(""),
factory.Get(""),
factory.Get(""),
factory.Get(""),
factory.Get(""),
factory.Get(""),
factory.Get(""),
}
for _, s := range stamps {
s.Print()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.