Skip to content

Instantly share code, notes, and snippets.

@nasust
Created December 4, 2016 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasust/6cf8c210cfc4ebe2f029a2990f4c1639 to your computer and use it in GitHub Desktop.
Save nasust/6cf8c210cfc4ebe2f029a2990f4c1639 to your computer and use it in GitHub Desktop.
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