本文介绍: 享元模式从对象中剥离出不发生改变且多个实例需要的重复数据,独立出一个享元,使多个对象共享,从而节省内存以及减少对象数量。
享元模式从对象中剥离出不发生改变且多个实例需要的重复数据,独立出一个享元,使多个对象共享,从而节省内存以及减少对象数量。
flyweight.go
package flyweight
import "fmt"
type ImageFlyweightFactory struct {
maps map[string]*ImageFlyweight
}
var imageFactory *ImageFlyweightFactory
func GetImageFlyweightFactory() *ImageFlyweightFactory {
if imageFactory == nil {
imageFactory = &ImageFlyweightFactory{
maps: make(map[string]*ImageFlyweight),
}
}
return imageFactory
}
func (f *ImageFlyweightFactory) Get(filename string) *ImageFlyweight {
image := f.maps[filename]
if image == nil {
image = NewImageFlyweight(filename)
f.maps[filename] = image
}
return image
}
type ImageFlyweight struct {
data string
}
func NewImageFlyweight(filename string) *ImageFlyweight {
// Load image file
data := fmt.Sprintf("image data %s", filename)
return &ImageFlyweight{
data: data,
}
}
func (i *ImageFlyweight) Data() string {
return i.data
}
type ImageViewer struct {
*ImageFlyweight
}
func NewImageViewer(filename string) *ImageViewer {
image := GetImageFlyweightFactory().Get(filename)
return &ImageViewer{
ImageFlyweight: image,
}
}
func (i *ImageViewer) Display() {
fmt.Printf("Display: %sn", i.Data())
}
flyweight_test.go
package flyweight
import "testing"
func ExampleFlyweight() {
viewer := NewImageViewer("image1.png")
viewer.Display()
// Output:
// Display: image data image1.png
}
func TestFlyweight(t *testing.T) {
viewer1 := NewImageViewer("image1.png")
viewer2 := NewImageViewer("image1.png")
if viewer1.ImageFlyweight != viewer2.ImageFlyweight {
t.Fail()
}
}
原文地址:https://blog.csdn.net/qq_45704048/article/details/135467517
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_55948.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。