Skip to content

Instantly share code, notes, and snippets.

@tgreiser
Created September 21, 2016 19:21
Show Gist options
  • Save tgreiser/d5bc9da5bf76904c5b09210e43c73fa1 to your computer and use it in GitHub Desktop.
Save tgreiser/d5bc9da5bf76904c5b09210e43c73fa1 to your computer and use it in GitHub Desktop.
Functional Dependency Injection example
package main
import "log"
// Our container
type Application struct {
DB Database
}
// Interface for a system component
type Database struct {
SampleFunc func() string
}
// General mock implementation
func MockDatabase() Database {
db := Database{}
db.SampleFunc = func() string {
return "base"
}
return db
}
func main() {
db := MockDatabase()
log.Print(db.SampleFunc())
db.SampleFunc = func() string {
return "injected!"
}
log.Print(db.SampleFunc())
a := Application{MockDatabase()}
log.Print(a.DB.SampleFunc())
a.DB.SampleFunc = func() string {
return "injected via app container"
}
log.Print(a.DB.SampleFunc())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment