Created
September 21, 2016 19:21
-
-
Save tgreiser/d5bc9da5bf76904c5b09210e43c73fa1 to your computer and use it in GitHub Desktop.
Functional Dependency Injection example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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