组合模式在Go中通过接口+嵌入+递归实现统一处理Leaf和Composite:定义Component接口,Leaf实现基础行为,Composite聚合子节点并递归委托,客户端透明调用无需类型判断。

组合模式(Composite Pattern)在 Go 语言中不依赖继承和抽象类,而是通过接口 + 嵌入(embedding)+ 递归结构来实现统一处理单个对象(Leaf)和组合对象(Composite)。核心是定义一个公共行为接口,让两者都实现它,从而在调用侧无需区分类型。
先定义一个 Component 接口,声明所有节点共有的行为,比如 Operation()、GetPrice() 或 Add(Component)(仅 Composite 需要,Leaf 可空实现或 panic):
// Component 定义通用行为
type Component interface {
Operation() string
GetPrice() float64
}
// Leaf 实现接口,不包含子节点
type Leaf struct {
name string
price float64
}
func (l Leaf) Operation() string { return "Leaf: " + l.name }
func (l Leaf) GetPrice() float64 { return l.price }
Composite 结构体嵌入切片保存子 Component,并实现相同接口。关键在于:其方法内部递归调用子节点的同名方法,把“组合”逻辑封装在自身内:
迷你天猫商城是一个基于Spring Boot的综合性B2C电商平台,需求设计主要参考天猫商城的购物流程:用户从注册开始,到完成登录,浏览商品,加入购物车,进行下单,确认收货,评价等一系列操作。 作为迷你天猫商城的核心组成部分之一,天猫数据管理后台包含商品管理,订单管理,类别管理,用户管理和交易额统计等模块,实现了对整个商城的一站式管理和维护。所有页面均兼容IE10及以上现代浏览器。部署方式1、项目
0
// Composite 持有多个 Component
type Composite struct {
name string
children []Component // 存储 interface 类型,支持 Leaf 和其他 Composite
}
func (c *Composite) Add(child Component) {
c.children = append(c.children, child)
}
func (c *Composite) Operation() string {
result := "Composite: " + c.name + "\n"
for _, child := range c.children {
result += "\t" + child.Operation() + "\n"
}
return result
}
func (c *Composite) GetPrice() float64 {
sum := 0.0
for _, child := range c.children {
sum += child.GetPrice()
}
return sum
}
调用方只依赖 Component 接口,无论是传入 Leaf 还是 *Composite,都能直接调用方法。递归结构自动展开,真正实现“统一处理”:
立即学习“go语言免费学习笔记(深入)”;
func main() {
leaf1 := Leaf{name: "USB Cable", price: 12.5}
leaf2 := Leaf{name: "Mouse", price: 49.9}
subComp := &Composite{name: "Peripherals"}
subComp.Add(leaf1)
subComp.Add(leaf2)
root := &Composite{name: "Desktop Setup"}
root.Add(subComp)
root.Add(Leaf{name: "Monitor", price: 299.0})
fmt.Println(root.Operation())
fmt.Printf("Total Price: $%.2f\n", root.GetPrice())
}
// 输出自动包含层级缩进和总价,客户端无感知内部结构
Add() 方法;若误调用,可在 Composite 的 Add 中加 nil 检查或 panic 提示Add() 等方法操作Iterator() Iterator 方法,返回自定义迭代器strings.Builder 替代 += 拼接以上就是如何使用Golang实现组合模式_统一处理单个对象和组合对象的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号