-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathcomposite.go
More file actions
91 lines (74 loc) · 2.38 KB
/
Copy pathcomposite.go
File metadata and controls
91 lines (74 loc) · 2.38 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package composite
import (
"fmt"
"reflect"
)
////////////////////////////////
//使用集装箱与货物的例子
//下面三个是对象的该模式的关键结构
////////////////////////////////
//Cargo class 基本的货物类型可以被继承
type Cargo struct {
Volume uint //货物需要要尺寸
Description string //描述
}
//GetCargoType return type
func (c *Cargo) GetCargoType() string {
return reflect.TypeOf(c).String()
}
//ShowContent return type
func (c *Cargo) ShowContent() {
typeName := reflect.TypeOf(c).String()
fmt.Println("Type: ", typeName, " Content ", c.Description)
}
//Box 复合类型,表示集装箱
//Box 复合类型,集装箱里面装具体的货物,也可以继续放箱子
type Box struct {
Cargo //继承货物类
InnerSpace uint //内部空间
Children []interface{} //有子对象
}
//PutInCargo 增加新的能力
//PutInCargo (cargo ICargo) //放入一个子类型
func (b *Box) PutInCargo(cargo interface{}) {
switch cargo.(type) {
case *Box:
fmt.Println("get a Box: Type: ", cargo.(*Box).GetCargoType())
case *SingleCargo:
fmt.Println("get a SingleCargo Type: ", cargo.(*SingleCargo).GetCargoType())
}
b.Children = append(b.Children, cargo)
}
//GetChildren () []ICompositedCargo
func (b *Box) GetChildren() []interface{} {
return b.Children
}
//ShowContent 覆盖继承实现
//ShowContent display children content
func (b *Box) ShowContent() {
typeName := reflect.TypeOf(b).String()
fmt.Println("Type: ", typeName, " InnerSpace ", b.InnerSpace, " Children: ", b.Description)
count := len(b.Children)
fmt.Println("Children Count: ", count, " Description ", b.Description)
for _, child := range b.Children {
//判断类型
switch child.(type) {
case *Box:
fmt.Println("Current Child is a Box: Type cast to (*Box) ")
child.(*Box).ShowContent()
case *SingleCargo:
fmt.Println("Current Child is a Single Cargo: Type cast to (*SingleCargo) ")
child.(*SingleCargo).ShowContent()
}
}
}
//SingleCargo 具体的非复合类型,对应多叉树的叶子节点
type SingleCargo struct {
Cargo //继承货物类,具有基本的货物熟悉
From, To string //货是从谁发到谁的
}
//ShowContent return type
func (s *SingleCargo) ShowContent() {
typeName := reflect.TypeOf(s).String()
fmt.Println("Type: ", typeName, " From ", s.From, " To ", s.To, " Content ", s.Description)
}