forked from AlexanderGrom/go-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathflyweight.go
41 lines (35 loc) · 954 Bytes
/
flyweight.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Package flyweight is an example of the Flyweight Pattern.
package flyweight
// Flyweighter interface
type Flyweighter interface {
GetName() string
SetName(name string)
}
// FlyweightFactory implements a factory.
// If a suitable flyweighter is in pool, then returns it.
type FlyweightFactory struct {
pool map[int]Flyweighter
}
// GetFlyweight creates or returns a suitable Flyweighter by state.
func (f *FlyweightFactory) GetFlyweight(state int) Flyweighter {
if f.pool == nil {
f.pool = make(map[int]Flyweighter)
}
if _, ok := f.pool[state]; !ok {
f.pool[state] = &ConcreteFlyweight{state: state}
}
return f.pool[state]
}
// ConcreteFlyweight implements a Flyweighter interface.
type ConcreteFlyweight struct {
state int
name string
}
// GetName returns name
func (f *ConcreteFlyweight) GetName() string {
return "My name: " + f.name
}
// SetName sets a name
func (f *ConcreteFlyweight) SetName(name string) {
f.name = name
}