Golang设计模式之享元模式

Jackey Golang 2,314 次浏览 , , 没有评论

创建文件ImageFlyWeight.go

package FlyWeight

import "fmt"

type ImageFlyWeight struct {
    data string
}

// 初始化
func NewImageFlyWeight(filename string) *ImageFlyWeight {
    data := fmt.Sprintf("image data %s", filename)
    return &ImageFlyWeight{data}
}

func (i *ImageFlyWeight) Data() string {
    return i.data
}

创建文件ImageFlyWeightFactory.go

package FlyWeight

var imgFlyFactory *ImageFlyWeightFactory

type ImageFlyWeightFactory struct {
    maps map[string]*ImageFlyWeight
}

// 对象初始化,不会反复初始化
func GetImageFlyWeightFactory() *ImageFlyWeightFactory {
    if imgFlyFactory == nil {
        imgFlyFactory = &ImageFlyWeightFactory{make(map[string]*ImageFlyWeight)}
    }
    return imgFlyFactory
}

func (i *ImageFlyWeightFactory) Get(filename string) *ImageFlyWeight {
    image := i.maps[filename] // 取出,去掉重复
    if image == nil {
        image = NewImageFlyWeight(filename) // 存储进入
        i.maps[filename] = image
    }
    return image
}

创建文件ImageViewer.go

package FlyWeight

import "fmt"

type ImageViewer struct {
    *ImageFlyWeight
}

func NewImageViewer(filename string) *ImageViewer {
    image := GetImageFlyWeightFactory().Get(filename)
    return &ImageViewer{image}
}

func (i *ImageViewer) Display() {
    fmt.Sprintf("Display %s\n", i.Data())
}

main.go

package main

import (
    "fmt"
    "ssp_api_go/test/design/FlyWeight"
)

func main() {
    v1 := FlyWeight.NewImageViewer("1.jpg")
    v1.Display()
    v2 := FlyWeight.NewImageViewer("1.jpg")
    v2.Display()
    if v1.ImageFlyWeight == v2.ImageFlyWeight {
        fmt.Println("节约内存")
    } else {
        fmt.Println("浪费内存")
    }
}

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Go