赞
踩
将对象组合成树形结构以表示“部分-整体”的层次结构。组合设计模式使得用户对单个对象和组合对象的使用具有一致性。
参与者
Component
为组合中的对象声明接口
Leaf
在组合中表示叶子节点对象。
Composite
存储子部件。访问和管理子部件。
component.go
package main
type Component interface {
Execute()
}
leaf.go
package main
import "fmt"
type Leaf struct {
name string
}
func (l *Leaf) Execute() {
fmt.Printf("%s leaf execute\n", l.name)
}
composite.go
package main import "fmt" type Composite struct { name string components []Component } func (cm *Composite) Execute() { fmt.Printf("%s composite execute\n", cm.name) for _, c := range cm.components { c.Execute() } } func (cm *Composite) Add(component Component) { cm.components = append(cm.components, component) }
client.go
package main
func main() {
composite1 := &Composite{name: "composite1"}
composite2 := &Composite{name: "composite2"}
leaf1 := &Leaf{name: "leaf1"}
leaf2 := &Leaf{name: "leaf2"}
leaf3 := &Leaf{name: "leaf3"}
composite2.Add(composite1)
composite1.Add(leaf1)
composite2.Add(leaf2)
composite2.Add(leaf3)
composite2.Execute()
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。