组合模式在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: $%.2fn”, root.GetPrice())
}
// 输出自动包含层级缩进和总价,客户端无感知内部结构