mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-23 12:26:03 +03:00
60 lines
1.1 KiB
Go
60 lines
1.1 KiB
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())
|
||
|
}
|