File tree Expand file tree Collapse file tree 3 files changed +81
-0
lines changed Expand file tree Collapse file tree 3 files changed +81
-0
lines changed Original file line number Diff line number Diff line change
1
+ # 原型模式
2
+
3
+ 原型模式使对象能复制自身,并且暴露到接口中,使客户端面向接口编程时,不知道接口实际对象的情况下生成新的对象。
4
+
5
+ 原型模式配合原型管理器使用,使得客户端在不知道具体类的情况下,通过接口管理器得到新的实例,并且包含部分预设定配置。
Original file line number Diff line number Diff line change
1
+ package prototype
2
+
3
+ //Cloneable 是原型对象需要实现的接口
4
+ type Cloneable interface {
5
+ Clone () Cloneable
6
+ }
7
+
8
+ type PrototypeManager struct {
9
+ prototypes map [string ]Cloneable
10
+ }
11
+
12
+ func NewPrototypeManager () * PrototypeManager {
13
+ return & PrototypeManager {
14
+ prototypes : make (map [string ]Cloneable ),
15
+ }
16
+ }
17
+
18
+ func (p * PrototypeManager ) Get (name string ) Cloneable {
19
+ return p .prototypes [name ]
20
+ }
21
+
22
+ func (p * PrototypeManager ) Set (name string , prototype Cloneable ) {
23
+ p .prototypes [name ] = prototype
24
+ }
Original file line number Diff line number Diff line change
1
+ package prototype
2
+
3
+ import "testing"
4
+
5
+ var manager * PrototypeManager
6
+
7
+ type Type1 struct {
8
+ name string
9
+ }
10
+
11
+ func (t * Type1 ) Clone () Cloneable {
12
+ tc := * t
13
+ return & tc
14
+ }
15
+
16
+ type Type2 struct {
17
+ name string
18
+ }
19
+
20
+ func (t * Type2 ) Clone () Cloneable {
21
+ tc := * t
22
+ return & tc
23
+ }
24
+
25
+ func TestClone (t * testing.T ) {
26
+ t1 := manager .Get ("t1" )
27
+
28
+ t2 := t1 .Clone ()
29
+
30
+ if t1 == t2 {
31
+ t .Fatal ("error! get clone not working" )
32
+ }
33
+ }
34
+
35
+ func TestCloneFromManager (t * testing.T ) {
36
+ c := manager .Get ("t1" ).Clone ()
37
+
38
+ t1 := c .(* Type1 )
39
+ if t1 .name != "type1" {
40
+ t .Fatal ("error" )
41
+ }
42
+
43
+ }
44
+
45
+ func init () {
46
+ manager = NewPrototypeManager ()
47
+
48
+ t1 := & Type1 {
49
+ name : "type1" ,
50
+ }
51
+ manager .Set ("t1" , t1 )
52
+ }
You can’t perform that action at this time.
0 commit comments