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

组合设计模式

简介

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

参与者

  • Component

    为组合中的对象声明接口

  • Leaf

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

  • Composite

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

案例1

component.go

go 复制代码
package main

type Component interface {
	Execute()
}

leaf.go

go 复制代码
package main

import "fmt"

type Leaf struct {
	name string
}

func (l *Leaf) Execute() {
	fmt.Printf("%s leaf execute\n", l.name)
}

composite.go

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

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()
}
相关推荐
初圣魔门首席弟子3 分钟前
const string getWord() ;和 string getWord() const ;是一样的效果吗
开发语言·c++
lly20240616 分钟前
Docker 安装 Node.js
开发语言
明天会有多晴朗21 分钟前
C语言入门教程(第6讲):函数——让程序学会“分工合作”的魔法
c语言·开发语言·算法
泽虞25 分钟前
《Qt应用开发》笔记p3
linux·开发语言·数据库·c++·笔记·qt·面试
晓风残月淡26 分钟前
JVM字节码与类的加载(一):类的加载过程详解
开发语言·jvm·python
XXYBMOOO29 分钟前
如何自定义 Qt 日志处理并记录日志到文件
开发语言·数据库·qt
知南x32 分钟前
【QT界面设计学习篇】qt快速开发技巧
开发语言·qt
hqyjzsb36 分钟前
2025 年项目管理转型白皮书:AI 驱动下的能力重构与跨域突破
开发语言·人工智能·重构·产品经理·编程语言·caie
奶茶树1 小时前
【C++】12.多态(超详解)
开发语言·c++
草莓熊Lotso1 小时前
《算法闯关指南:优选算法--二分查找》--17.二分查找(附二分查找算法简介),18. 在排序数组中查找元素的第一个和最后一个位置
开发语言·c++·算法