定義
組合模式也叫合成模式,有時又叫做部分-整體模式,主要是用來描述部分與整體的關係,將物件組合成樹形結構以表示「部分-整體」的層次結構,使得使用者對單個物件和組合物件的使用具有一致性
結構
組合模式包含三個角色:
使用場景
優缺點**示例
例如,大型公司就是乙個典型的組合模式應用的例子,大型公司有總部,還在每個區設定有分部,有可能還在每個城市都設有辦事處,而且每個分部或者辦事處都具有和總部一樣的公司架構。我們下面就以這個為模型實現golang的組合模式。
// 組合模式統一物件和物件集,使得使用相同介面使用物件和物件集。
// 組合模式常用於樹狀結構,用於統一葉子節點和樹節點的訪問,並且可以用於應用某一操作到所有子節點。
package main
import (
"fmt"
"strings"
)type icompany inte***ce
type concretecompany struct
func newconcretecompany(name string) *concretecompany ,}}
func (c *concretecompany) add(comp icompany)
func (c *concretecompany) remove(comp icompany)
func (c *concretecompany) display(depth int)
}func (c *concretecompany) lineofduty()
}type hrdepartment struct
func newhrdepartment(name string) *hrdepartment
}func (h *hrdepartment) add(comp icompany)
func (h *hrdepartment) remove(comp icompany)
func (h *hrdepartment) display(depth int)
func (h *hrdepartment) lineofduty()
type financedepartment struct
func newfinancedepartment(name string) *financedepartment
}func (f *financedepartment) add(comp icompany)
func (f *financedepartment) remove(comp icompany)
func (f *financedepartment) display(depth int)
func (f *financedepartment) lineofduty()
func main()
mysql樹形結構查詢子節點
需求 在樹形的節點關係下,比如選單樹或者檔案目錄樹,要想獲取某個節點的所有子節點,或者所有父類節點,在知道節點樹最大層級的情況下,可以直接通過一條sql直接查詢實現 表結構 id,parent id eg 已知節點樹深度不超過10,查詢id 100010的節點的所有子節點 select org.id...
結構型 3 組合模式
1.模式機動 資料夾 容器 container 檔案 葉子 leaf 如何將容器物件和葉子物件進行遞迴組合,使得使用者在使用時無須對它們進行區分,可以一致地對待容器物件和葉子物件?組合模式 2.模式定義 3.模式結構 組合模式包含如下角色 模式結構 檔案系統組合模式結構圖 透明組合模式 水果盤 例項...
MySQL中用函式方法獲取樹形結構節點的深度
思路 學習了用mysql函式查詢乙個節點所有子節點,但是沒找著如何實現查詢節點的深度。但轉念一想,只要反向查出所有父節點不就好了嗎,因為節點與父節點總是一一對應的,所以只要查出父節點列表就等於得到了深度 表結構 create table hospital user id varchar 36 not...