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.缺点:++

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

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

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

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

相关推荐
杨充20 小时前
10.可测试性实战设计
设计模式·开源·代码规范
杨充20 小时前
9.重构十二式的实战
设计模式·开源·代码规范
杨充20 小时前
6.设计原则的全景图
设计模式·开源·全栈
杨充20 小时前
2.面向对象的特性
设计模式
杨充20 小时前
7.SOLID原则案例汇
设计模式·开源·全栈
杨充20 小时前
8.反模式与坏味道
设计模式·开源·代码规范
杨充20 小时前
3.接口vs抽象类比较
设计模式
咖啡八杯1 天前
文法、BNF与AST
java·设计模式·解释器模式·ast·文法
咖啡八杯1 天前
GoF设计模式——解释器模式
java·后端·spring·设计模式