关于设计模式:设计模式组合Component模式

1次阅读

共计 1110 个字符,预计需要花费 3 分钟才能阅读完成。

模式定义

将对象组合成树形构造以示意“局部 – 整体”的层次结构,Composite 使得用户对单个对象和组合对象的应用具备一致性(稳固)

类图

要点总结

  • Composite 模式采纳树形构造来实现普遍存在的对象容器,从而将“一对多”的关系转化为“一对一”的关系,使得客户代码能够统一地(复用)解决对象和对象容器,无需关系解决的是单个的对象,还是组合的对象容器
  • 将“客户代码与简单的对象容器构造”解耦是 Composite 的核心思想解耦之后,客户代码将于纯正的形象接口 – 而给对象容器的外部实现构造 – 产生依赖,从而更能“应答变动”
  • Composite 模式在具体实现中,能够让父对象中的子对象反向追溯,如果父对象有频繁的遍历需要,可应用缓存技巧来改善效率

Go 语言代码实现

工程目录

composite.go

package Composite

import "fmt"

type Component interface {Traverse()
}

type Leaf struct {value int}

func NewLeaf (value int) *Leaf{return &Leaf{value: value}
}

func (l *Leaf) Traverse() {fmt.Println(l.value)
}

type Composite struct {children []Component
}

func NewComposite() * Composite{return &Composite{children: make([]Component, 0)}
}
func (c *Composite) Add (component Component) {c.children = append(c.children, component)
}

func (c *Composite) Traverse() {
   for idx, _ := range c.children{c.children[idx].Traverse()}
}

composite_test.go

package Composite

import (
   "fmt"
   "testing"
)

func TestComposite_Traverse(t *testing.T) {containers := make([]Composite, 4)
   for i := 0; i< 4; i++ {
      for j := 0; j < 3 ; j++ {containers[i].Add(NewLeaf(i * 3 + j))
      }
   }

   for i := 0; i < 4; i++ {containers[0].Add(&containers[i])
   }
   for i := 0; i < 4; i++{containers[i].Traverse()
      fmt.Printf("Finished\n")
   }
}
正文完
 0