-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcomposite_test.go
55 lines (44 loc) · 947 Bytes
/
composite_test.go
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
package composite
import (
"testing"
"github.com/stretchr/testify/assert"
)
// 组合模式
// 组织接口,实现统计人数的功能
type IOrganization interface {
Count() int
}
// 员工
type Employee struct {
Name string
}
func (e *Employee) Count() int {
return 1
}
// 部门
type Department struct {
Name string
SubOrganizations []IOrganization
}
func (d *Department) Count() int {
c := 0
for _, org := range d.SubOrganizations {
c += org.Count()
}
return c
}
func (d *Department) AddSub(org IOrganization) {
d.SubOrganizations = append(d.SubOrganizations, org)
}
func NewOrganization() IOrganization {
root := &Department{Name: "root"}
for i := 0; i < 10; i++ {
root.AddSub(&Employee{})
root.AddSub(&Department{Name: "sub", SubOrganizations: []IOrganization{&Employee{}}})
}
return root
}
func TestNewOrganization(t *testing.T) {
got := NewOrganization().Count()
assert.Equal(t, 20, got)
}