Skip to content

Instantly share code, notes, and snippets.

@oleksii-demedetskyi
Last active April 8, 2016 07:19
Show Gist options
  • Save oleksii-demedetskyi/737a820ce86b77e5f957 to your computer and use it in GitHub Desktop.
Save oleksii-demedetskyi/737a820ce86b77e5f957 to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
protocol Cat {
func meow() -> String
}
protocol Dog {
func bark() -> String
}
class Smokey : Cat {
func meow() -> String {
return "Meeooow"
}
}
class Buddy : Dog {
func bark() -> String {
return "Woof"
}
}
protocol ServiceLocator {
func getService<T>() -> T;
}
class Client {
let cat : Cat
let dog : Dog
init(locator: ServiceLocator) {
cat = locator.getService()
dog = locator.getService()
}
func makeNoise() -> String {
return "Cat goes \(cat.meow()), dog goes \(dog.bark())"
}
}
protocol ServiceContainer {
var locator: ServiceLocator {get}
func registerService<T>(service: T)
}
class SimpleContainer : ServiceContainer, ServiceLocator {
var locator: ServiceLocator { return self }
private var registry : [String: Any] = [:]
func registerService<T>(service: T) {
let key = "\(T.self)"
registry[key] = service
}
func getService<T>() -> T {
let key = "\(T.self)"
return registry[key] as! T
}
}
let serviceContainer = SimpleContainer() as ServiceContainer
serviceContainer.registerService(Smokey() as Cat)
serviceContainer.registerService(Buddy() as Dog)
let client = Client(locator: serviceContainer.locator)
client.makeNoise() // "Cat goes Meeooow, dog goes Woof"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment