go设计模式之组合设计模式

组合设计模式

简介

将对象组合成树形结构以表示“部分-整体”的层次结构。组合设计模式使得用户对单个对象和组合对象的使用具有一致性。

参与者

  • Component

    为组合中的对象声明接口

  • Leaf

    在组合中表示叶子节点对象。

  • Composite

    存储子部件。访问和管理子部件。

案例1

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()
}

相关推荐

  1. go设计模式组合设计模式

    2024-04-30 09:50:03       15 阅读
  2. 设计模式组合模式

    2024-04-30 09:50:03       10 阅读
  3. go 设计模式观察者模式

    2024-04-30 09:50:03       30 阅读
  4. go设计模式工厂方法模式

    2024-04-30 09:50:03       13 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-30 09:50:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-30 09:50:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-30 09:50:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-30 09:50:03       20 阅读

热门阅读

  1. 解决拉取多个不同git项目下的ssh问题

    2024-04-30 09:50:03       12 阅读
  2. 【Python快速上手(四)】

    2024-04-30 09:50:03       15 阅读
  3. 【Golang】Gin 框架的多种类型绑定函数

    2024-04-30 09:50:03       13 阅读
  4. Android Room 数据库中的 Journal mode 解释

    2024-04-30 09:50:03       13 阅读
  5. 【Spring AI】07. 提示词

    2024-04-30 09:50:03       11 阅读
  6. Verilog学习之时序控制、语句块(1)

    2024-04-30 09:50:03       12 阅读
  7. Caddy实践 | Docker环境下使用Caddy快速部署web服务器

    2024-04-30 09:50:03       11 阅读
  8. memcpy,memmove函数详解

    2024-04-30 09:50:03       15 阅读
  9. 云容器与云中间件

    2024-04-30 09:50:03       11 阅读