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()
}
相关推荐
道199321 分钟前
python实现电脑手势识别截图
开发语言·python
奇树谦22 分钟前
Qt 自定义菜单栏 / 工具栏按钮 QToolButton + InstantPopup 详细解析
开发语言·数据库·qt
草莓熊Lotso23 分钟前
Git 本地操作入门:版本控制基础、跨平台部署与仓库核心流程
开发语言·人工智能·经验分享·git·后端·架构·gitee
CS_浮鱼24 分钟前
【C++进阶】异常
开发语言·c++
百锦再30 分钟前
大话Rust的前生今世
开发语言·后端·rust·go·内存·时间·抽象
QT 小鲜肉34 分钟前
【C++基础与提高】第十一章:面向对象编程进阶——继承与多态
java·linux·开发语言·c++·笔记·qt
点云SLAM1 小时前
Boost库中Boost.PropertyTree使用和实战示例
开发语言·c++·josn·boost库·参数读取
lly2024061 小时前
CSS3 分页技术解析
开发语言