Skip to content

Commit ad60e3c

Browse files
committed
add flyweight
1 parent b054c8d commit ad60e3c

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

18_flyweight/README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# 享元模式
2+
3+
享元模式从对象中剥离出不发生改变且多个实例需要的重复数据,独立出一个享元,使多个对象共享,从而节省内存以及减少对象数量。
4+

18_flyweight/flyweight.go

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package flyweight
2+
3+
import "fmt"
4+
5+
type ImageFlyweightFactory struct {
6+
maps map[string]*ImageFlyweight
7+
}
8+
9+
var imageFactory *ImageFlyweightFactory
10+
11+
func GetImageFlyweightFactory() *ImageFlyweightFactory {
12+
if imageFactory == nil {
13+
imageFactory = &ImageFlyweightFactory{
14+
maps: make(map[string]*ImageFlyweight),
15+
}
16+
}
17+
return imageFactory
18+
}
19+
20+
func (f *ImageFlyweightFactory) Get(filename string) *ImageFlyweight {
21+
image := f.maps[filename]
22+
if image == nil {
23+
image = NewImageFlyweight(filename)
24+
f.maps[filename] = image
25+
}
26+
27+
return image
28+
}
29+
30+
type ImageFlyweight struct {
31+
data string
32+
}
33+
34+
func NewImageFlyweight(filename string) *ImageFlyweight {
35+
// Load image file
36+
data := fmt.Sprintf("image data %s", filename)
37+
return &ImageFlyweight{
38+
data: data,
39+
}
40+
}
41+
42+
func (i *ImageFlyweight) Data() string {
43+
return i.data
44+
}
45+
46+
type ImageViewer struct {
47+
*ImageFlyweight
48+
}
49+
50+
func NewImageViewer(filename string) *ImageViewer {
51+
image := GetImageFlyweightFactory().Get(filename)
52+
return &ImageViewer{
53+
ImageFlyweight: image,
54+
}
55+
}
56+
57+
func (i *ImageViewer) Display() {
58+
fmt.Printf("Display: %s\n", i.Data())
59+
}

18_flyweight/flyweight_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package flyweight
2+
3+
import "testing"
4+
5+
func ExampleFlyweight() {
6+
viewer := NewImageViewer("image1.png")
7+
viewer.Display()
8+
// Output:
9+
// Display: image data image1.png
10+
}
11+
12+
func TestFlyweight(t *testing.T) {
13+
viewer1 := NewImageViewer("image1.png")
14+
viewer2 := NewImageViewer("image1.png")
15+
16+
if viewer1.ImageFlyweight != viewer2.ImageFlyweight {
17+
t.Fail()
18+
}
19+
}

0 commit comments

Comments
 (0)