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()
}
相关推荐
泡海椒10 小时前
jquick-pdf 表格行列尺寸控制实战:单元格合并的可行边界
java·开发语言·pdf
Zane199410 小时前
策略模式现在该不该上?一次讲清楚过度设计和设计不足怎么找平衡
设计模式
纪念 22911 小时前
c++类和对象(四)
开发语言·c++
辛苦才能11 小时前
C++多态原理:虚函数表的内存布局与动态绑定的汇编真相
开发语言·c++
铲灰12 小时前
做个总结而已
开发语言
IvanCodes12 小时前
Python 文件操作(十二):文件与目录的读写
开发语言·python
她说..12 小时前
常见设计模式-模板方法模式
java·spring·设计模式·springboot
神仙别闹20 小时前
基于 C++ 实现(控制台)学生成绩管理系统
开发语言·c++
伞伞悦读20 小时前
【第36期】Python 目录与路径详解:pathlib、文件遍历、创建、复制、移动和删除风险
开发语言·python
xiaofeiyang15021 小时前
第六章 · 桥接 — 三支毛笔,画出九种颜色
设计模式