创建文件:Component.go
package Composite //有的时候是父节点,叶子 type Component interface { Parent() Component SetParent(Component) Name() string SetName(string) AddChild(Component) Print(string) } const ( LeafNode = iota CompositeNode ) type component struct { parent Component name string } func NewComponent(kind int, name string) Component { var c Component switch kind { case LeafNode: //根据不同的类型 c = NewLeaf() case CompositeNode: c = NewComposite() } c.SetName(name) return c } func (c *component) Parent() Component { return c.parent } func (c *component) SetParent(parent Component) { c.parent = parent } func (c *component) Name() string { return c.name } func (c *component) SetName(name string) { c.name = name } func (c *component) AddChild(child Component) { } func (c *component) Print(string2 string) { }
创建文件:Leafs.go
package Composite import "fmt" type Leaf struct { component } func NewLeaf() *Leaf { // 开辟一个叶子 return &Leaf{} } func (c *Leaf) Print(pre string) { fmt.Println(pre, c.Name()) } type Composite struct { component childs []Component // 叶子集合 } // 创建一个组合结构体 func NewComposite() *Composite { return &Composite{childs: make([]Component, 0)} } func (c *Composite) AddChild(child Component) { child.SetParent(c) c.childs = append(c.childs, child) } func (c *Composite) Print(pre string) { // 打印显示每一个节点 fmt.Println(pre, c.name) pre += " " for _, comp := range c.childs { comp.Print(pre) } }
main.go
package main import "test/design/Composite" func main() { root := Composite.NewComponent(Composite.CompositeNode, "root") r1 := Composite.NewComponent(Composite.CompositeNode, "r1") r2 := Composite.NewComponent(Composite.CompositeNode, "r2") r3 := Composite.NewComponent(Composite.CompositeNode, "r3") l1 := Composite.NewComponent(Composite.LeafNode, "l1") l2 := Composite.NewComponent(Composite.LeafNode, "l2") l3 := Composite.NewComponent(Composite.LeafNode, "l3") root.AddChild(r1) root.AddChild(r2) root.AddChild(r3) r1.AddChild(l1) r2.AddChild(l2) r3.AddChild(l3) root.Print("") }