组合模式
定义: 将一组对象组织成树形结构,以表示一种“部分-整体”的层次结构,组合让客户端(代码使用者)可以统一单个对象和组合对象的处理逻辑
应用场景:业务场景必须能够表示成树形结构;将一组对象组织成树形结构,将单个对象和组合对象都看做树中的节点,以统一处理逻辑,并且它利用树形结构的特点,递归处理每个子树,一次简化代码实现。
代码实现
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
| package design
type IOrganization interface { Count() int }
type Employee struct { Name string }
func (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 }
|
单元测试
1 2 3 4 5 6 7 8 9 10 11
| package design
import ( "testing" "github.com/stretchr/testify/assert" )
func TestNewOrganization(t *testing.T) { got := NewOrganization().Count() assert.Equal(t, 20, got) }
|