乐趣区

关于设计模式:设计模式享元Flyweight模式

模式定义

使用共享技术无效地反对大量细粒度的对象

类图

利用场景

如果零碎有大量相似的对象,能够应用享元模式

长处

如果零碎有大量相似的对象,能够节俭大量的内存及 CPU 资源

要点总结

要点总结

  • 如果零碎有解耦实现对象的代价问题,Flyweight 次要解决面向对象的代价问题,个别不涉及面向对象的抽象性问题
  • Flyweight 采纳对象共享的做法来升高零碎中对象的个数,从而升高细粒度对象给零碎带来的内存压力。在具体实现方面,要留神对象状态的解决
  • 对象的数量太大从而导致对象内存开销加大 – 什么样的数量才算大?这须要咱们认真的依据具体利用状况进行评估,而不能凭空臆断

Go 语言代码实现

工程目录

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"])
}
退出移动版