結構型:六. 組合模式
阿新 • • 發佈:2022-04-01
組合模式是什麼
組合模式:是一種結構型設計模式, 你可以使用它將物件組合成樹狀結構, 並且能像使用獨立物件一樣使用它們。
為什麼用組合模式
如果你需要實現樹狀物件結構,可以使用組合模式。確保應用的核心模型能夠以樹狀結構表示。 嘗試將其分解為簡單元素和容器。 記住,容器必須能夠同時包含簡單元素和其他容器。
組合模式怎麼實現
這裡是模擬搜尋資料夾和檔案,資料夾裡面有資料夾和檔案。組成一個樹狀的結構。
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") }
優點
- 你可以利用多型和遞迴機制更方便地使用複雜樹結構。
- 遵循開閉原則。 無需更改現有程式碼, 你就可以在應用中新增新元素, 使其成為物件樹的一部分。
缺點
- 設計較複雜,客戶端需要花更多時間理清類之間的層次關係。
- 不容易限制容器中的構件。