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()
}
相关推荐
重生成为码农‍23 分钟前
类加载机制
java·开发语言·jvm
Ai 编码助手32 分钟前
PHP与Python无缝融合,开启跨语言开发新纪元
开发语言·python·php
19岁开始学习33 分钟前
PHP之依赖注入
android·开发语言·php
小丁爱养花37 分钟前
MyBatis-Plus:告别手写 SQL 的高效之道
java·开发语言·后端·spring·mybatis
ππ记录43 分钟前
python3.13.2安装详细步骤(附安装包)
linux·开发语言·python·python3.13.2安装·python 3.13.2下载·python3.13.2·python 3.13.2
修修修也1 小时前
【C++11】左值引用、右值引用、移动语义和完美转发
开发语言·c++·学习·c++11
Pandaconda1 小时前
【新人系列】Golang 入门(七):闭包详解
开发语言·经验分享·笔记·后端·golang·go·闭包
HXQ_晴天1 小时前
Bash 脚本基础
开发语言·chrome·bash
清@尘1 小时前
威联通 后台可用命令查看Bash
开发语言·chrome·bash
为什么要内卷,摆烂不香吗1 小时前
【无标题】
开发语言·php