设计模式-享元模式

设计模式-享元模式

一、定义

  享元模式(Flyweight Pattern):运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,它是一种对象结构型模式。

二、代码实现

基本对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 享元对象
type ObjFlyweight struct {
data string // 数据
}

// 构造
func NewObjFlyweight(objname string) *ObjFlyweight {
data := fmt.Sprintf("data %s", objname)
return &ObjFlyweight{
data: data,
}
}

func (o *ObjFlyweight) Data() string {
return o.data
}

对象管理器(对象工厂)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
func (f *ObjFlyweightFactory) Get(objname string) *ObjFlyweight {
obj := f.maps[objname]
// 取对象,没有就New一个
if obj == nil {
obj = NewObjFlyweight(objname)
f.maps[objname] = obj
}
return obj
}

type ObjFlyweightFactory struct {
maps map[string]*ObjFlyweight
}

var g_ObjFactory *ObjFlyweightFactory

func GetObjFlyweightFactory() *ObjFlyweightFactory {
if g_ObjFactory == nil {
g_ObjFactory = &ObjFlyweightFactory{
maps: make(map[string]*ObjFlyweight),
}
}
return g_ObjFactory
}

显示对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
type ObjDisplay struct {
*ObjFlyweight
}

func NewObjDisplay(objname string) *ObjDisplay {
obj := GetObjFlyweightFactory().Get(objname)
return &ObjDisplay{
ObjFlyweight: obj,
}
}

func (odisp *ObjDisplay) Display() {
fmt.Printf("Display: %s\n", odisp.Data())
}

三、测试用例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// 样例输出测试
func ExampleFlyweight() {
odisp := NewObjDisplay("obj1")
odisp.Display()
// Output:
// Display: data obj1
}

// 结果显示如下:
=== RUN ExampleFlyweight
--- PASS: ExampleFlyweight (0.00s)
PASS

Process finished with exit code 0

------------------------------------------------------
// 对象测试
func TestFlyweight(t *testing.T) {
odisp1 := NewObjDisplay("obj1")
odisp2 := NewObjDisplay("obj2")
odisp3 := NewObjDisplay("obj1")

if odisp1.ObjFlyweight != odisp2.ObjFlyweight {
t.Fail()
}

if odisp3.ObjFlyweight == odisp1.ObjFlyweight {
t.Log("Pass")
}
}

// 结果输出如下:
=== RUN TestFlyweight
TestFlyweight: flyweight_test.go:24: Pass
--- FAIL: TestFlyweight (0.00s)
FAIL

Process finished with exit code 1
评论

:D 一言句子获取中...

加载中,最新评论有1分钟缓存...