Last active
November 19, 2019 16:50
-
-
Save chunkyguy/26437e2c802b07e4ccb4440aa073c359 to your computer and use it in GitHub Desktop.
Service Locator Pattern with GameplayKit
This file contains 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
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() |
This file contains 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
class AccessibilityService { | |
var isGrayscale: Bool { | |
return UIAccessibility.shouldDifferentiateWithoutColor | |
} | |
} |
This file contains 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
func registerServices() { | |
SL.register(service: AccessibilityService()) | |
} |
This file contains 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
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