Combination mode
Composition is a structural design pattern that you can use to combine objects into tree structures and use them like you would with independent objects.
Combinations are very popular solutions for most problems that require spanning tree structures. The main function of combination is to call methods recursively on the entire tree structure and summarize the results.
Concept example
Let's try to understand the combination pattern using an example of an operating system file system. There are two types of objects in the file system: files and folders. In some cases, files and folders should be treated as the same objects. This is the time for the combination mode to come into play.
Imagine that you need to search for specific keywords in the file system. This search operation needs to be applied to both files and folders. For files, it only looks at the contents of the file; for folders, keywords are found in all files inside it.
: Component interface
package main import "fmt" type File struct { name string } func (f *File) search(keyword string) { ("Searching for keyword %s in file %s\n", keyword, ) } func (f *File) getName() string { return }
: Combination
package main import "fmt" type Folder struct { components []Component name string } func (f *Folder) search(keyword string) { ("Serching recursively for keyword %s in folder %s\n", keyword, ) for _, composite := range { (keyword) } } func (f *Folder) add(c Component) { = append(, c) }
: leaf
package main type Component interface { search(string) }
: Client code
package main func main() { file1 := &File{name: "File1"} file2 := &File{name: "File2"} file3 := &File{name: "File3"} folder1 := &Folder{ name: "Folder1", } (file1) folder2 := &Folder{ name: "Folder2", } (file2) (file3) (folder1) ("rose") }
: Execution results
Serching recursively for keyword rose in folder Folder2
Searching for keyword rose in file File2
Searching for keyword rose in file File3
Serching recursively for keyword rose in folder Folder1
Searching for keyword rose in file File1
This is the article about the explanation of the combination mode of Golang design mode. For more relevant Go combination mode content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!