|
| 1 | +# Flyweight |
| 2 | + |
| 3 | +This pattern it's very commonly used in computer graphics and the video game |
| 4 | +industry. It allow sharing the state of a heavy object between many instances of |
| 5 | +some type. |
| 6 | + |
| 7 | +This example uses a creational pattern to create objects instance. |
| 8 | + |
| 9 | +```go |
| 10 | +func TestFactoryCreatesObjects(t *testing.T) { |
| 11 | + f := NewObjectFactory() |
| 12 | + firstObject := f.GetObject(TYPE_ONE) |
| 13 | + if firstObject == nil { |
| 14 | + t.Error("The pointer to the TYPE_ONE was nil") |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +``` |
| 19 | + |
| 20 | +According to the flyweight pattern, each object requested is returned. Well, |
| 21 | +what is really returned is not an object but a pointer to that object. |
| 22 | + |
| 23 | +```go |
| 24 | +func TestFactoryCreatesTwoObjects(t *testing.T) { |
| 25 | + f := NewObjectFactory() |
| 26 | + _ = f.GetObject(TYPE_ONE) |
| 27 | + secondObject := f.GetObject(TYPE_ONE) |
| 28 | + if secondObject == nil { |
| 29 | + t.Error("The pointer to the TYPE_ONE was nil") |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +``` |
| 34 | + |
| 35 | +Each pointer created is a different pointer. |
| 36 | + |
| 37 | +```go |
| 38 | +func TestFactoryCreatesJustObjectOfTypes(t *testing.T) { |
| 39 | + f := NewObjectFactory() |
| 40 | + firstObject := f.GetObject(TYPE_ONE) |
| 41 | + secondObject := f.GetObject(TYPE_ONE) |
| 42 | + if firstObject != secondObject { |
| 43 | + t.Error("TYPE_ONE pointers weren't the same") |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +``` |
| 48 | + |
| 49 | +Even if object of TYPE_ONE is requested more times, the number of created |
| 50 | +objects is equals to the number of type requested. |
| 51 | + |
| 52 | +```go |
| 53 | +func TestNumberOfObjectsIsAlwaysNumberOfTypeOfObjectCreated(t *testing.T) { |
| 54 | + f := NewObjectFactory() |
| 55 | + _ = f.GetObject(TYPE_ONE) |
| 56 | + _ = f.GetObject(TYPE_ONE) |
| 57 | + if f.GetNumberOfObjects() != 1 { |
| 58 | + t.Errorf( |
| 59 | + "The number of objects created was not 1: %d\n", |
| 60 | + f.GetNumberOfObjects(), |
| 61 | + ) |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +``` |
| 66 | + |
| 67 | +Finally, and for completeness, if two objects are requested a huge amount of |
| 68 | +time, the number of object created is still two. |
| 69 | + |
| 70 | +```go |
| 71 | +func TestHighVolume(t *testing.T) { |
| 72 | + f := NewObjectFactory() |
| 73 | + objects := make([]*Object, 500000*2) |
| 74 | + for i := 0; i < 500000; i++ { |
| 75 | + objects[i] = f.GetObject(TYPE_ONE) |
| 76 | + } |
| 77 | + for i := 500000; i < 2*500000; i++ { |
| 78 | + objects[i] = f.GetObject(TYPE_TWO) |
| 79 | + } |
| 80 | + if f.GetNumberOfObjects() != 2 { |
| 81 | + t.Errorf( |
| 82 | + "The number of objects created was not 2: %d\n", |
| 83 | + f.GetNumberOfObjects(), |
| 84 | + ) |
| 85 | + } |
| 86 | +} |
| 87 | +``` |
0 commit comments