其他分享
首页 > 其他分享> > 结构型:六. 组合模式

结构型:六. 组合模式

作者:互联网

组合模式是什么

组合模式:是一种结构型设计模式, 你可以使用它将对象组合成树状结构, 并且能像使用独立对象一样使用它们。

为什么用组合模式

如果你需要实现树状对象结构,可以使用组合模式。确保应用的核心模型能够以树状结构表示。 尝试将其分解为简单元素和容器。 记住,容器必须能够同时包含简单元素和其他容器。

组合模式怎么实现

这里是模拟搜索文件夹和文件,文件夹里面有文件夹和文件。组成一个树状的结构。

folder.go
package composite

import "fmt"

type component interface {
    search(string)
}

type folder struct {
    components []component
    name       string
}

func (f *folder) search(keyword string) {
    fmt.Printf("Serching recursively for keyword %s in folder %s\n", keyword, f.name)
    for _, composite := range f.components {
        composite.search(keyword)
    }
}

func (f *folder) add(c component) {
    f.components = append(f.components, c)
}
file.go
package composite

import "fmt"

type file struct {
    name string
}

func (f *file) search(keyword string) {
    fmt.Printf("Searching for keyword %s in file %s\n", keyword, f.name)
}

main.go 客户端代码
func main() {
    file1 := &file{name: "File1"}
    file2 := &file{name: "File2"}
    file3 := &file{name: "File3"}

    folder1 := &folder{
        name: "Folder1",
    }
    folder2 := &folder{
        name: "Folder2",
    }

    folder1.add(file1)
    folder2.add(file2)
    folder2.add(file3)
    folder2.add(folder1)

    folder2.search("rose")
}

优点

  1. 你可以利用多态和递归机制更方便地使用复杂树结构。
  2. 遵循开闭原则。 无需更改现有代码, 你就可以在应用中添加新元素, 使其成为对象树的一部分。

缺点

  1. 设计较复杂,客户端需要花更多时间理清类之间的层次关系。
  2. 不容易限制容器中的构件。

标签:name,keyword,模式,add,组合,file,folder,string,结构型
来源: https://www.cnblogs.com/ourongxin/p/16089557.html