Skip to content

Instantly share code, notes, and snippets.

@mkock
Created January 13, 2020 21:47
Show Gist options
  • Save mkock/759d794bfd69d45a17d422a992174d3a to your computer and use it in GitHub Desktop.
Save mkock/759d794bfd69d45a17d422a992174d3a to your computer and use it in GitHub Desktop.
The Flyweight Pattern in Go, Example Two
// Player represents a player in a game.
type Player struct {
ID uint32
Handle, Name, Country string
Games []string
}
// cachedPlayer is a Player, but without the Games field.
type cachedPlayer struct {
ID uint32
Handle, Name, Country string
}
var games = []string{"Flappy Fish", "Ducks'n'Dogs", "Backflip Pro"}
var crashyGamesPlayers map[uint32]cachedPlayer
// convertWith returns the Player that matches cachedPlayer,
// with game titles attached.
func (c cachedPlayer) convertWith(games []string) Player {
return Player{
ID: c.ID,
Handle: c.Handle,
Name: c.Name,
Country: c.Country,
Games: games,
}
}
// FindPlayerByID returns the player with the given ID, if exists.
// Otherwise, an empty Player is returned.
func FindPlayerByID(ID uint32) Player {
if cp, ok := crashyGamesPlayers[ID]; ok {
// cachedPlayer found.
return cp.convertWith(games) // Using globally cached games.
}
return Player{}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment