Initial
This commit is contained in:
51
dependency_injection/main.go
Normal file
51
dependency_injection/main.go
Normal file
@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
|
||||
type Repository interface {
|
||||
Save(user *User) error
|
||||
}
|
||||
|
||||
type User struct {
|
||||
firstName string
|
||||
lastName string
|
||||
repository Repository
|
||||
}
|
||||
|
||||
func NewUser(firstName string, lastName string, repository Repository) *User {
|
||||
return &User{
|
||||
firstName: firstName,
|
||||
lastName: lastName,
|
||||
repository: repository,
|
||||
}
|
||||
}
|
||||
|
||||
func (u User) Save() {
|
||||
u.repository.Save(&u)
|
||||
}
|
||||
|
||||
type DbRepository struct {
|
||||
DbName string
|
||||
}
|
||||
|
||||
func (r DbRepository) Save(user *User) error {
|
||||
fmt.Printf("Saving %s %s to DB name %s...\n", user.firstName, user.lastName, r.DbName)
|
||||
return nil
|
||||
}
|
||||
|
||||
type ApiRepository struct {
|
||||
Url string
|
||||
}
|
||||
|
||||
func (r ApiRepository) Save(user *User) error {
|
||||
fmt.Printf("Saving %s %s to API url %s...\n", user.firstName, user.lastName, r.Url)
|
||||
return nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
pero := NewUser("Pero", "Perić", &DbRepository{DbName: "pero_db"})
|
||||
pero.Save()
|
||||
|
||||
mirko := NewUser("Mirko", "Mirković", &ApiRepository{Url: "http://pero.com"})
|
||||
mirko.Save()
|
||||
}
|
||||
Reference in New Issue
Block a user