Last active
September 3, 2015 07:49
-
-
Save randomstep/e7a6263a1f4b3a993cf9 to your computer and use it in GitHub Desktop.
show simple dependency injection EDIT: Ok really just dependency inheritance
This file contains hidden or 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
// do DI easy with protocol / extension? | |
class PostcardStore { | |
let postcards = ["France", "Romania"] | |
func calcPostage(from: String, to: String) -> Int { | |
return 42 // good enough until tests tell us otherwise | |
} | |
} | |
struct Context { | |
var notificationCenter = { | |
NSNotificationCenter.defaultCenter() | |
} | |
var locationManager = { | |
CLLocationManager() | |
} | |
} | |
protocol InjectableContext { | |
var postcardStore: PostcardStore { get } | |
var context: Context { get } | |
} | |
extension InjectableContext { | |
var postcardStore: PostcardStore { | |
return PostcardStore() | |
} | |
var context: Context { | |
return Context() | |
} | |
} | |
class Controller: InjectableContext { | |
// needs store! | |
func mailCards() { | |
let cards = postcardStore.postcards | |
let postage = postcardStore.calcPostage(cards.first!, to: cards.last!) | |
print(postage) | |
context.locationManager | |
} | |
} | |
let mainController = Controller() | |
mainController.mailCards() // should use DI so we can test |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I like the idea of having small, well-formed dependencies that vend specific sets of functionality. I whipped this example up in class quickly, to prove the language concept. the example needs much better structure and naming. To take it further, could have an "Injector" that tests for protocol conformance and if so sets the various properties.