Files
repo-pattern/app/inheritance/inheritance.go
2024-06-22 13:34:27 +02:00

75 lines
1.4 KiB
Go

package inheritance
import "fmt"
type Model struct{}
type MyModel struct {
Model
}
type MethodInitInterface interface {
Init(dbConn int)
}
type RepoBase[T interface{}] struct {
DbConn int
GetMethod[T]
ListMethod[T]
methods []MethodInitInterface
}
func (b *RepoBase[T]) InitMethods(dbConn int) {
for _, method := range b.methods {
method.Init(dbConn)
}
}
type CRUDRepo[T interface{}] struct {
RepoBase[T]
SaveMethod[T]
}
func (m *CRUDRepo[T]) Init(dbConn int) {
m.methods = []MethodInitInterface{&m.GetMethod, &m.ListMethod, &m.SaveMethod}
m.InitMethods(dbConn)
}
func DoInheritanceTest() {
repo := RepoBase[MyModel]{
DbConn: 111,
// GetMethod: GetMethod{
// DbConn: 666,
// },
// ListMethod: ListMethod{
// DbConn: 777,
// },
}
repo.GetMethod.Init(888)
repo.ListMethod.Init(888)
repo.GetMethod.Get()
repo.List()
fmt.Printf("outside Base: %d\n", repo.DbConn)
fmt.Printf("outside GetMethod: %d\n", repo.GetMethod.DbConn)
fmt.Printf("outside ListMethod: %d\n", repo.ListMethod.DbConn)
fmt.Println("----------------")
crudRepo := CRUDRepo[MyModel]{}
crudRepo.Init(999)
crudRepo.Get()
crudRepo.List()
crudRepo.Save()
fmt.Printf("outside GetMethod: %d\n", crudRepo.GetMethod.DbConn)
fmt.Printf("outside ListMethod: %d\n", crudRepo.ListMethod.DbConn)
fmt.Printf("outside SaveMethod: %d\n", crudRepo.SaveMethod.DbConn)
// repo.DbConn = 123
// repo.SomeGetVar = 456
// repo.DoSomething()
}