Go语言设计模式(七)组合模式

++组合模式是指将一组相似对象当做一个单一对象的设计模式.++

++1.组成角色:++

++1.1组件:++

++组合中的对象声明接口,主要用于访问和管理其子组件.++

++1.2叶子节点:++

++定义组合中原始对象行为的类.叶子节点表示组合中的叶对象.++

++1.3组合:++

++又称为容器,存储子组件并在组件接口中实现与子组件有关的类.++

++1.4客户端:++

++客户端可以通过组件接口操作组合中的对象.以及与树形结构中的所有项目交互.++

++2.使用场景:++

++2.1需要忽略组合对象和单个对象之间差异时.++

++2.2需要实现树形结构时.++

++2.3客户端以统一的方式处理简单或复杂的元素.++

3.实现:

3.1组件接口:
Go 复制代码
// 组件接口
type Component interface {
	Execute()
}
3.2叶节点类:
Go 复制代码
// 叶子节点类
type Leaf struct {
	value int
}

// 创建一个新的叶节点对象
func NewLeaf(value int) *Leaf {
	return &Leaf{value: value}
}

// 打印叶节点的值
func (l *Leaf) Execute() {
	fmt.Println(l.value)
}
3.3组合类:
Go 复制代码
// 组合类
type Composite struct {
	children []Component
}

// 创建一个新的组合对象
func NewComposite() *Composite {
	return &Composite{make([]Component, 0)}
}
3.4组合类中添加方法:
Go 复制代码
// 添加方法
func (c *Composite) Add(component Component) {
	c.children = append(c.children, component)
}

func (c *Composite) Execute() {
	for _, child := range c.children {
		child.Execute()
	}
}
3.5客户端:
Go 复制代码
func main() {
	composite := itboStudy.NewComposite()
	leaf := itboStudy.NewLeaf(99)
	leaf1 := itboStudy.NewLeaf(88)
	leaf2 := itboStudy.NewLeaf(77)
	composite.Add(leaf)
	composite.Add(leaf1)
	composite.Add(leaf2)
	composite.Execute()
}

4.实战:

4.1叶子节点:
Go 复制代码
// 叶子节点类
type Files struct {
	Name string
}

func (f *Files) Search(name string) {
	fmt.Printf("在文件%s中递归搜索%s", f.Name, name)
}

func (f *Files) GetName() string {
	return f.Name
}
4.2组合类:
Go 复制代码
// 定义组合类.
type Folders struct {
	Compents []Components
	Name     string
}

func (f *Folders) Search(name string) {
	fmt.Printf("在文件%s中递归搜索%s", f.Name, name)
	for i := range f.Compents {
		f.Compents[i].Search(name)
	}
}

func (f *Folders) Add(c Components) {
	f.Compents = append(f.Compents, c)
}
4.3组件接口:
Go 复制代码
// 定义组件接口
type Components interface {
	Search(name string)
}
4.4客户端:
Go 复制代码
func main() {
	file1 := &itboStudy.Files{Name: "itboStudy1"}
	file2 := &itboStudy.Files{Name: "itboStudy2"}
	file3 := &itboStudy.Files{Name: "itboStudy3"}
	folders := &itboStudy.Folders{Name: "itboFolder"}
	folders.Add(file1)
	folders.Add(file2)
	folders.Add(file3)
	folders.Search("99")
}

++5.优点:++

++无须了解构成树形结构的对象具体类,只需要调用接口方法.++

++客户端可以使用组件对象与复合结构中的对象进行交互.++

++如果调用的是叶子节点对象,可以直接处理请求.++

++如果调用的组合对象,组合模式会把请求转发给子组件.++

++6.缺点:++

++一旦定义了树结构,设计会过于笼统.++

++组合模式很难将树的组件限制为特定类型.++

++为了强制执行这种约束,程序必须依赖运行时检查.组合模式不能使用编程语言的类型系统.++

++士别三日当刮目相待.++

相关推荐
世洋Blog27 分钟前
开发思想-(数据驱动+组合模式)VS 继承
unity·组合模式·数据驱动
明洞日记27 分钟前
【设计模式手册011】享元模式 - 共享细粒度对象的高效之道
java·设计模式·享元模式
世洋Blog32 分钟前
开发思想-组合模式和接口多态的一点思考
c#·组合模式
帅中的小灰灰1 小时前
C++编程观察者设计模式
数据库·c++·设计模式
阿波罗尼亚2 小时前
Head First设计模式(六) 设计原则 命令模式
设计模式·命令模式
canonical_entropy5 小时前
模型驱动架构的数学内核:统一生成与演化的 Y = F(X) ⊕ Delta 不变式
数学·设计模式·架构
小毛驴8505 小时前
软件设计模式-代理模式
设计模式·系统安全·代理模式
雨中飘荡的记忆21 小时前
工厂模式详解
设计模式
Charles_go1 天前
C#42、什么是建造者设计模式
设计模式
烤麻辣烫1 天前
23种设计模式(新手)-3接口隔离原则
java·开发语言·学习·设计模式·intellij-idea