I'm OOP guy, recently I have to work on Golang the language that I haven't done it before. Though I already went through many articles talking about composition, I notice it's a bit tricky to use it properly on Golang
Let's say I have two examples of Golang composition, I don't know which one will be correct, and would it be different between of them? Thank you
First example
type BaseClass struct {
db *DB
}
func NewBaseClass(db *DB) *BaseClass {
return &BaseClass{db}
}
type ChildrenClass1 struct {
baseClass *BaseClass
}
func NewChildrenClass1(db *DB) *ChildrenClass1 {
baseClass := NewBaseClass(db)
return &ChildrenClass1{baseClass}
}
type ChildrenClass2 struct {
baseClass *BaseClass
}
func NewChildrenClass2(db *DB) *ChildrenClass2 {
baseClass := NewBaseClass(db)
return &ChildrenClass2{baseClass}
}
func main(){
db := NewDB()
chilrend1 := NewChildrenClass1(db)
chilrend2 := NewChildrenClass2(db)
}
Second example
type BaseClass struct {
db *DB
}
func NewBaseClass(db *DB) *BaseClass {
return &BaseClass{db}
}
type ChildrenClass1 struct {
baseClass *BaseClass
}
func NewChildrenClass1(baseClass *BaseClass) *ChildrenClass1 {
return &ChildrenClass1{baseClass}
}
type ChildrenClass2 struct {
baseClass *BaseClass
}
func NewChildrenClass2(baseClass *BaseClass) *ChildrenClass2 {
return &ChildrenClass2{baseClass}
}
func main(){
db := NewDB()
baseClass := NewBaseClass(db)
chilrend1 := NewChildrenClass1(baseClass)
chilrend2 := NewChildrenClass2(baseClass)
}
Aucun commentaire:
Enregistrer un commentaire