1 回答

TA貢獻1936條經驗 獲得超7個贊
在 Go中,您可能找不到像在許多其他基于 OOP 的語言中那樣定義組合或聚合的正確方法。這只是因為Go 沒有類,沒有對象,沒有異常,也沒有模板。
但是 Go 有結構。結構是用戶定義的類型。結構類型(帶有方法)的用途與其他語言中的類類似。
說了這么多,讓我們看看一些常見的定義,看看我們能做什么:
組合意味著孩子不能獨立于父母而存在的關系。示例:房屋(父)和房間(子)。房間不存在獨立于房屋[ 1 ]。
另一方面,聚合意味著孩子可以獨立于父母而存在的關系。示例:教室(家長)和學生(孩子)。刪除教室,學生仍然存在[ 1 ]。
因此,在聚合和組合中,“實例”“擁有”另一種類型的對象。但是有一個微妙的區別:聚合意味著子可以獨立于父而存在的關系。組合意味著孩子不能獨立于父母而存在的關系。
到目前為止,這就是我們現在從composition中所知道的:
沒有父母,孩子就無法存在
組合是指將更簡單的類型組合成更復雜的類型
當然,我們主要使用它來重用代碼
回答您的問題: 兩者看起來都正確,但是,
第一個例子更接近于composition,因為沒有父母,孩子就不會存在;
第二個例子更像是一個聚合,因為如果你刪除父級,子級將保持存在。
我重寫了您的代碼以嘗試舉例說明:
第一個例子重寫
package main
//Lamp struct is here to suppress the *DB that was in the original example
type Lamp struct {}
type Room struct {
Lamps *[]Lamp
}
func NewRoom(l *[]Lamp) *Room {
return &Room{l}
}
type House1 struct {
Room *Room
}
func NewHouse1(l *[]Lamp) *House1 {
r := NewRoom(l)
return &House1{r}
}
type House2 struct {
Room *Room
}
func NewHouse2(l *[]Lamp) *House2 {
r := NewRoom(l)
return &House2{r}
}
func main(){
lamps := []Lamp{}
house1 := NewHouse1(&lamps)
house2 := NewHouse2(&lamps)
}
第二個例子重寫:
package main
type LibraryCard struct {}
type Student struct {
LibCard *LibraryCard
}
func NewStudent(l *LibraryCard) *Student {
return &Student{l}
}
type Classroom1 struct {
Student *Student
}
func NewClassroom1(s *Student) *Classroom1 {
return &Classroom1{s}
}
type Classroom2 struct {
Student *Student
}
func NewClassroom2(s *Student) *Classroom2 {
return &Classroom2{s}
}
func main(){
lc := new(LibraryCard)
student := NewStudent(lc)
classroom1 := NewClassroom1(student)
classroom2 := NewClassroom2(student)
}
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報