Skip to content

Instantly share code, notes, and snippets.

@werediver
Last active January 14, 2019 06:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save werediver/f00f23dbfddfd646f96c to your computer and use it in GitHub Desktop.
Save werediver/f00f23dbfddfd646f96c to your computer and use it in GitHub Desktop.
Basic Service Locator pattern implementation in Swift 2.
protocol ServiceLocator {
func getService<T>() -> T?
}
final class BasicServiceLocator: ServiceLocator {
// Service registry
private lazy var reg: Dictionary<String, Any> = [:]
private func typeName(some: Any) -> String {
return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
}
func addService<T>(service: T) {
let key = typeName(T)
reg[key] = service
//print("Service added: \(key) / \(typeName(service))")
}
func getService<T>() -> T? {
let key = typeName(T)
return reg[key] as? T
}
}
// Demo
// Services declaration
protocol S1 {
func f1() -> String
}
protocol S2 {
func f2() -> String
}
// Services imlementation
class S1Impl: S1 {
func f1() -> String {
return "S1 OK"
}
}
class S2Impl: S2 {
func f2() -> String {
return "S2 OK"
}
}
// Service Locator initialization
let sl: ServiceLocator = {
let sl = BasicServiceLocator()
sl.addService(S1Impl() as S1)
sl.addService(S2Impl() as S2)
return sl
}()
// Test run
let s1: S1? = sl.getService()
let s2: S2? = sl.getService()
print(s1?.f1() ?? "S1 NOT FOUND") // S1 OK
print(s2?.f2() ?? "S2 NOT FOUND") // S2 OK
@volkdmitri
Copy link

Good implementation 👍 I've just made some changes. Take a look at it https://gist.github.com/volkdmitri/8757016cfca83764f380

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment