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()
}
相关推荐
杰瑞不懂代码5 分钟前
基于 MATLAB 的 AM/DSB-SC/VSB 模拟调制与解调仿真及性能对比研究
开发语言·matlab·语音识别·am·dsb-sc·vsb
霁月的小屋12 分钟前
从Vue3与Vite的区别切入:详解Props校验与组件实例
开发语言·前端·javascript·vue.js
趣知岛21 分钟前
初识DeepSeek
开发语言·人工智能·deepseek
superman超哥22 分钟前
仓颉编译器优化揭秘:尾递归优化的原理与实践艺术
开发语言·后端·仓颉编程语言·仓颉·仓颉语言·尾递归·仓颉编译器
lkbhua莱克瓦2425 分钟前
基础-SQL-DML
开发语言·数据库·笔记·sql·mysql
独自破碎E28 分钟前
说一下消息队列有哪些模型
java·开发语言
saber_andlibert30 分钟前
【C++转GO】初阶知识
开发语言·c++·golang
小笔学长34 分钟前
Mixin 模式:灵活组合对象功能
开发语言·javascript·项目实战·前端开发·mixin模式
IT艺术家-rookie35 分钟前
golang--解决 Go 并发场景下的数据竞争问题的方案
golang
我是人机不吃鸭梨35 分钟前
Flutter 桌面端开发终极指南(2025版):构建跨平台企业级应用的完整解决方案
开发语言·javascript·人工智能·flutter·架构