[设计模式 Go实现] 结构型~享元模式

享元模式从对象中剥离出不发生改变且多个实例需要的重复数据,独立出一个享元,使多个对象共享,从而节省内存以及减少对象数量。

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: %s\n", 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()
    }
}

相关推荐

  1. [设计模式 Go实现] 结构模式

    2024-01-09 10:18:02       37 阅读
  2. GO设计模式——13、模式结构

    2024-01-09 10:18:02       37 阅读
  3. 设计模式结构设计模式——模式

    2024-01-09 10:18:02       19 阅读
  4. 设计模式结构设计模式模式

    2024-01-09 10:18:02       9 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-09 10:18:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-09 10:18:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-09 10:18:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-09 10:18:02       18 阅读

热门阅读

  1. js实现点击音频实现播放功能

    2024-01-09 10:18:02       39 阅读
  2. Flutter循环遍历数组获取索引值

    2024-01-09 10:18:02       41 阅读
  3. Spark避坑系列二(Spark Core-RDD编程)

    2024-01-09 10:18:02       46 阅读
  4. Redis启动方式

    2024-01-09 10:18:02       38 阅读
  5. 正则表达式—split()拆分

    2024-01-09 10:18:02       35 阅读
  6. 手机的恢复功能急需改进

    2024-01-09 10:18:02       39 阅读