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()
}
相关推荐
Never_Satisfied12 分钟前
C#获取汉字拼音字母方法总结
开发语言·c#
zh_xuan25 分钟前
kotlin 密封类
开发语言·kotlin
码小猿的CPP工坊34 分钟前
C++软件开发之内存泄漏闭坑方法
开发语言·c++
Ethan-D37 分钟前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
满栀5851 小时前
分页插件制作
开发语言·前端·javascript·jquery
froginwe111 小时前
C 标准库 - <stdio.h>
开发语言
zwtahql1 小时前
php源码级别调试
开发语言·php
qq_406176141 小时前
深入剖析JavaScript原型与原型链:从底层机制到实战应用
开发语言·前端·javascript·原型模式
{Hello World}2 小时前
Java抽象类与接口深度解析
java·开发语言
jiaguangqingpanda2 小时前
Day22-20260118
java·开发语言