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()
}
相关推荐
Python学习导航1 分钟前
Python开源项目月排行 2025年10月
开发语言·python
爱吃巧克力的程序媛3 分钟前
Qt 异步编程---概述
开发语言·qt
feifeigo12311 分钟前
MATLAB实现两组点云ICP配准
开发语言·算法·matlab
Yang-Never11 分钟前
Open GL ES->以指定点为中心缩放图片纹理的完整图解
android·java·开发语言·kotlin·android studio
fengfuyao98513 分钟前
粒子群算法(PSO)求解标准VRP问题的MATLAB实现
开发语言·算法·matlab
dangdang___go31 分钟前
文件操作c语言
c语言·开发语言
塔能物联运维34 分钟前
设备断网时数据丢失,后来启用本地缓存+异步重传队列
java·开发语言·缓存
天涯路s1 小时前
qt怎么自定义日志
开发语言·qt
张较瘦_1 小时前
[论文阅读] 软件工程 - 供应链 | 从Log4Shell到Go组件漏洞:一篇文看懂开源依赖安全的核心痛点与解决方案
论文阅读·golang·开源
Evand J1 小时前
【自适应IMM】MATLAB编写的创新多模型,基于CA/CT双模型和观测自适应。二维平面目标位置估计,带误差统计特性输出,附代码下载链接
开发语言·matlab·ekf·imm·交互式多模型