组合模式
简介
组合模式(Composite Pattern)是指将一组相似的对象当做一个单一对象的设计模式
适用场景
对大部分需要生成树形结构的问题来说,组合模式都是非常受欢迎的解决方案。组合模式的主要功能是在整个树形结构上递归调用直接计算方法并对计算结果进行汇总。
优点
nil
缺点
nil
示例代码
Go
package compositepatterns
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)
}
func (f *File) GetName() string {
return f.Name
}
type Component interface {
Search(string)
}
type Folder struct {
Components []Component
Name string
}
func (f *Folder) Search(keyword string) {
fmt.Printf("Searching recursively for keyword %s in folder %s\n", keyword, f.Name)
for _, component := range f.Components {
component.Search(keyword)
}
}
func (f *Folder) Add(c Component) {
f.Components = append(f.Components, c)
}
测试
package compositepatterns
import (
"testing"
)
func TestComposite(t *testing.T) {
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")
}