The schema definition

Use sharing techniques to effectively support a large number of fine-grained objects

The class diagram

Application scenarios

If the system has a large number of similar objects, you can use the Endowment pattern

advantages

If your system has a large number of similar objects, you can save a lot of memory and CPU resources

The point to summarize

The point to summarize

  • If the system has the cost of decoupling the implementation of objects, Flyweight mainly addresses the cost of object-oriented, and generally does not address the abstraction of object-oriented issues
  • Flyweight uses object sharing to reduce the number of objects in the system, thus reducing the memory burden of fine-grained objects on the system. In the concrete implementation, attention should be paid to the handling of object state
  • The number of objects is too large to cause object memory overhead — what number is too large? This requires careful evaluation based on specific applications, not just assumptions

Go language code implementation

Project directory

flyweight.go

package Flyweight type FlyWeight struct { Name string } func NewFlyWeight (name string) *FlyWeight{ return &FlyWeight{Name: name} } type FlyWeightFactory struct { pool map[string]*FlyWeight } func NewFlyWeightFactory() *FlyWeightFactory { return &FlyWeightFactory{pool: make(map[string]*FlyWeight)} } func (f *FlyWeightFactory) GetFlyWeight (name string) *FlyWeight { weight, ok := f.pool[name] if ! ok { weight = NewFlyWeight(name) f.pool[name] = weight } return weight }

flyweight_test.go

package Flyweight

import "testing"
import "github.com/stretchr/testify/assert"

func TestFlyWeightFactory_GetFlyWeight(t *testing.T) {
   factory := NewFlyWeightFactory()
   hong := factory.GetFlyWeight("hong beauty")
   xiang := factory.GetFlyWeight("xiang beauty")

   assert.Len(t, factory.pool, 2)
   assert.Equal(t, hong, factory.pool["hong beauty"])
   assert.Equal(t, xiang, factory.pool["xiang beauty"])
}