组合模式是一种结构型设计模式,它允许将对象组合成树形结构以表示"部分-整体"层次结构。它使得用户对单个对象和组合对象的使用具有一致性。
在Go中,可以使用接口来实现组合模式。让我们看一个简单的示例:
package main
import "fmt"
type Component interface {
Operation() string
}
type Leaf struct {
name string
}
func (l *Leaf) Operation() string {
return fmt.Sprintf("Leaf %s", l.name)
}
type Composite struct {
name string
components []Component
}
func (c *Composite) Operation() string {
var result string
for _, comp := range c.components {
result += comp.Operation() + "\n"
}
return fmt.Sprintf("Branch %s includes: \n%s", c.name, result)
}
func (c *Composite) Add(component Component) {
c.components = append(c.components, component)
}
func (c *Composite) Remove(name string) {
for i, comp := range c.components {
if comp.Operation() == name {
c.components = append(c.components[:i], c.components[i+1:]...)
}
}
}
func main() {
leaf1 := &Leaf{name: "A"}
leaf2 := &Leaf{name: "B"}
leaf3 := &Leaf{name: "C"}
branch1 := &Composite{name: "Branch 1"}
branch1.Add(leaf1)
branch1.Add(leaf2)
branch2 := &Composite{name: "Branch 2"}
branch2.Add(leaf3)
root := &Composite{name: "Root"}
root.Add(branch1)
root.Add(branch2)
fmt.Println(root.Operation())
}
在上面的代码中,我们定义了一个Component接口,有一个Operation()方法,用于返回组合对象的描述。我们还定义了一个Leaf结构体,它实现了Component接口,其Operation()方法返回一个描述符,Composite结构体也实现了Component接口。其中Composite结构体包含一个成员变量components,存储在组合模式中子组件的引用。Add()和Remove()方法被用于添加或移除子组件。
我们定义了几个叶子节点和分支节点。然后,我们将这些节点组合成了一棵树,并打印出了整个树形结构。我们可以看到,组合模式允许我们以一个一致的方式来处理单个对象和组合对象。这就是组合模式的核心思想。