Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Last active November 19, 2019 16:50
Show Gist options
  • Save chunkyguy/26437e2c802b07e4ccb4440aa073c359 to your computer and use it in GitHub Desktop.
Save chunkyguy/26437e2c802b07e4ccb4440aa073c359 to your computer and use it in GitHub Desktop.
Service Locator Pattern with GameplayKit
private class ServiceWrapper<T>: GKComponent {
let service: T
init(service: T) {
self.service = service
super.init()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ServiceLocator {
private let registry = GKEntity()
func register<T>(service: T) {
registry.addComponent(ServiceWrapper(service: service))
}
func get<T>() -> T? {
registry.component(ofType: ServiceWrapper<T>.self)?.service
}
var featureFlagService: FeatureFlagService? { return get() }
var networkService: NetworkService? { return get() }
var accessibilityService: AccessibilityService? { return get() }
}
let SL = ServiceLocator()
class AccessibilityService {
var isGrayscale: Bool {
return UIAccessibility.shouldDifferentiateWithoutColor
}
}
func registerServices() {
SL.register(service: AccessibilityService())
}
func getColor(hue: CGFloat) -> UIColor {
let isGrayscale = SL.accessibilityService?.isGrayscale ?? false
if isGrayscale {
return UIColor(white: hue, alpha: 1.0)
} else {
return UIColor(hue: hue, saturation: 0.7, brightness: 0.8, alpha: 1.0)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment