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()
}
相关推荐
java1234_小锋3 分钟前
简述Mybatis的插件运行原理?
java·开发语言·mybatis
charlie11451419118 分钟前
勇闯前后端Week2:后端基础——HTTP与REST
开发语言·网络·笔记·网络协议·学习·http
福尔摩斯张1 小时前
二维数组详解:定义、初始化与实战
linux·开发语言·数据结构·c++·算法·排序算法
大佬,救命!!!1 小时前
C++函数式策略模式代码练习
开发语言·c++·学习笔记·学习方法·策略模式·迭代加深·多文件编译
T***16071 小时前
JavaScript打包
开发语言·javascript·ecmascript
qq_336313931 小时前
java基础-常用的API
java·开发语言
道一231 小时前
C# 读取文件方法介绍
开发语言·c#
蒋星熠1 小时前
常见反爬策略与破解反爬方法:爬虫工程师的攻防实战指南
开发语言·人工智能·爬虫·python·网络安全·网络爬虫
是店小二呀1 小时前
在家搭个私人影院?LibreTV+cpolar,随时随地看片自由
开发语言·人工智能