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()
}
相关推荐
Yvonne爱编码3 分钟前
深入剖析 Java 中的深拷贝与浅拷贝:原理、实现与最佳实践
java·开发语言
索荣荣8 分钟前
Java关键字终极指南:从入门到精通
java·开发语言
悟能不能悟8 分钟前
SimpleDateFormat 为什么线程不安全
开发语言·安全
沉默-_-12 分钟前
掌握Maven:高效Java项目构建与管理
java·开发语言·后端·maven
一晌小贪欢13 分钟前
Python 魔术方法实战:深度解析 Queue 模块的模块化设计与实现
开发语言·分布式·爬虫·python·python爬虫·爬虫分布式
wangbing112514 分钟前
从lambda 表达式引用的本地变量必须是最终变量或实际上的最终变量
java·开发语言
txinyu的博客22 分钟前
常见设计模式
设计模式
奔跑的web.22 分钟前
TypeScript namespace 详解:语法用法与使用建议
开发语言·前端·javascript·vue.js·typescript
倾国倾城的反派修仙者30 分钟前
鸿蒙开发——使用弹窗授权保存媒体库资源
开发语言·前端·华为·harmonyos
电化学仪器白超30 分钟前
③YT讨论
开发语言·python·单片机·嵌入式硬件