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()
}
相关推荐
蒋星熠19 分钟前
字母异位词分组(每天刷力扣hot100系列)
开发语言·c++·算法·leetcode·职场和发展
杨航 AI29 分钟前
PHP 5.5 Action Management with Parameters (English Version)
android·开发语言·php
代码的余温35 分钟前
Java试题-选择题(2)
java·开发语言
lemon_sjdk37 分钟前
java笔记——ConcurrentLinkedQueue
java·开发语言·笔记
封奚泽优1 小时前
使用Python制造扫雷游戏
开发语言·python·游戏·pygame·扫雷·random
超浪的晨1 小时前
Maven 与单元测试:JavaWeb 项目质量保障的基石
java·开发语言·学习·单元测试·maven·个人开发
魂尾ac1 小时前
因为想开发新项目了~~要给老Python项目整个虚拟环境
开发语言·python
不会理财的程序员不是好老板1 小时前
Java Spring Boot项目中集成Swagger完整步骤
java·开发语言·spring boot
Murphy_lx2 小时前
C++多态的原理
java·开发语言·c++
程序员编程指南3 小时前
Qt 移动应用发布与分发指南
c语言·开发语言·c++·qt