Skip to content

Commit

Permalink
add flyweight
Browse files Browse the repository at this point in the history
  • Loading branch information
senghoo committed Apr 7, 2016
1 parent b054c8d commit ad60e3c
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
4 changes: 4 additions & 0 deletions 18_flyweight/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# 享元模式

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

59 changes: 59 additions & 0 deletions 18_flyweight/flyweight.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
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())
}
19 changes: 19 additions & 0 deletions 18_flyweight/flyweight_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
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()
}
}

0 comments on commit ad60e3c

Please sign in to comment.