zoukankan      html  css  js  c++  java
  • DesignPatternFlyweight享元模式

    DesignPatternFlyweight享元模式

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

    一个map[interface{}]interface{}加上断言就能解决的事情,不知道为啥绕一圈

    官方代码

    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
    ", i.Data())
    }
    
    
    # 测试代码
    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()
    	}
    }
    
  • 相关阅读:
    React native的static propTypes
    修改react native 的工程名
    react native的flatList
    react native获取键盘高度
    git reactNativeBle
    rn踩坑记录
    docker学习3-镜像的基本使用
    docker学习2-搭建centos7-python3.6环境
    docker学习1-CentOS 7安装docker环境
    Python3数据库封装
  • 原文地址:https://www.cnblogs.com/maomaomaoge/p/14118752.html
Copyright © 2011-2022 走看看