Last active
January 14, 2019 06:13
-
-
Save werediver/f00f23dbfddfd646f96c to your computer and use it in GitHub Desktop.
Basic Service Locator pattern implementation in Swift 2.
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good implementation 👍 I've just made some changes. Take a look at it https://gist.github.com/volkdmitri/8757016cfca83764f380