如何使用Golang实现组合模式_统一处理单个对象和组合对象

1次阅读

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

如何使用Golang实现组合模式_统一处理单个对象和组合对象

组合模式(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,并实现相同接口。关键在于:其方法内部递归调用子节点的同名方法,把“组合”逻辑封装在自身内:

如何使用Golang实现组合模式_统一处理单个对象和组合对象

迷你天猫商城

迷你天猫商城是一个基于Spring Boot的综合性B2C电商平台,需求设计主要参考天猫商城的购物流程:用户从注册开始,到完成登录,浏览商品,加入购物车,进行下单,确认收货,评价等一系列操作。 作为迷你天猫商城的核心组成部分之一,天猫数据管理后台包含商品管理,订单管理,类别管理,用户管理和交易额统计等模块,实现了对整个商城的一站式管理和维护。所有页面均兼容IE10及以上现代浏览器。部署方式1、项目

如何使用Golang实现组合模式_统一处理单个对象和组合对象 0

查看详情 如何使用Golang实现组合模式_统一处理单个对象和组合对象

  // 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())
}
  // 输出自动包含层级缩进和总价,客户端无感知内部结构

注意事项与实用技巧

  • Go 没有“强制实现”机制,Leaf 不应实现 Add() 方法;若误调用,可在 Composite 的 Add 中加 nil 检查或 panic 提示
  • 为避免意外修改,Composite 的 children 切片建议不暴露为公开字段,只通过 Add() 等方法操作
  • 如需支持遍历(如深度优先),可额外添加 Iterator() Iterator 方法,返回自定义迭代器
  • 性能敏感场景下,避免频繁分配字符串;可用 strings.Builder 替代 += 拼接

text=ZqhQzanResources