flyweight.go
package flyweight import ( "time" ) const ( TEAM_A = "A" TEAB_B = "B" ) type Team struct { ID uint64 Name string Shield []byte Players []Player HistoricalData []HistoricalData } type Player struct { Name string Surname string PerviousTeam uint64 Photo []byte } type HistoricalData struct { Year uint8 LeagueResults []Match } type Match struct { Date time.Time VisitorID uint64 LocalID uint64 LocalScore byte VisitorScore byte LocalShoots uint16 VisitorShoots uint16 } type teamFlyweightFactory struct { createdTeams map[string]*Team } func (t *teamFlyweightFactory) GetTeam(teamID string) *Team { if t.createdTeams[teamID] != nil { return t.createdTeams[teamID] } team := getTeamFactory(teamID) t.createdTeams[teamID] = &team return t.createdTeams[teamID] } func getTeamFactory(team string) Team { switch team { case TEAB_B: return Team{ ID: 2, Name: TEAB_B, } default: return Team{ ID: 1, Name: TEAM_A, } } } func (t *teamFlyweightFactory) GetNumberOfObjects() int { return len(t.createdTeams) } func NewTeamFactory() teamFlyweightFactory { return teamFlyweightFactory{ createdTeams: make(map[string]*Team), } }
flyweight_test.go
package flyweight import ( "fmt" "testing" ) func TestTeamFlyweightFactory_GetTeam(t *testing.T) { factory := NewTeamFactory() teamA1 := factory.GetTeam(TEAM_A) if teamA1 == nil { t.Error("The pointer to the TEAM_A was nil") } teamA2 := factory.GetTeam(TEAM_A) if teamA2 == nil { t.Error("The pointer to the TEAM_A was nil") } if teamA1 != teamA2 { t.Error("TEAM_A pointers weren't the same") } if factory.GetNumberOfObjects() != 1 { t.Errorf("The number of objects created was not 1: %d\n", factory.GetNumberOfObjects()) } } func Test_HighVolume(t *testing.T) { factory := NewTeamFactory() teams := make([]*Team, 5000*2) for i := 0; i < 5000; i++ { teams[i] = factory.GetTeam(TEAM_A) } for i := 5000; i < 2*5000; i++ { teams[i] = factory.GetTeam(TEAB_B) } if factory.GetNumberOfObjects() != 2 { t.Errorf("The number of objects created was not 2: %d\n", factory.GetNumberOfObjects()) } for i := 0; i < 3; i++ { fmt.Printf("Pointer %d points to %p and is located in %p\n", i, teams[i], &teams[i]) } }