Created
April 4, 2017 03:02
-
-
Save yoichitgy/ed807c3fb674e49b4a0f7863d5d26b56 to your computer and use it in GitHub Desktop.
Cake Pattern Example in Swift (Demo at iOSCon 2017 in London)
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
// Demo at iOSCon 2017 in London | |
// https://speakerdeck.com/yoichitgy/dependency-injection-in-practice-ioscon | |
// | |
// How to Use: Paste this program to a Playground. | |
// Tested with: Xcode 8.2.1 | |
// Interface (protocol) | |
protocol Logger { | |
func log(_ message: String) | |
} | |
protocol SocialService { | |
func fetchFollowers(callback: ([String]) -> Void) | |
} | |
// Implementation | |
struct PrintLogger: Logger { | |
func log(_ message: String) { | |
print("LOG: \(message)") | |
} | |
} | |
struct HardcodedSocialService: SocialService { | |
var logger: Logger? | |
func fetchFollowers(callback: ([String]) -> Void) { | |
let followers = ["Anya", "Yoichi"] | |
logger?.log("Fetch completed.") | |
callback(followers) | |
} | |
} | |
// Abstract Components | |
protocol LoggerComponent { | |
static var logger: Logger { get } | |
static func createLogger() -> Logger | |
} | |
protocol SocialServiceComponent { | |
static var socialService: SocialService { get } | |
static func createSocialService() -> SocialService | |
} | |
// Concrete Components | |
protocol PrintLoggerComponent: LoggerComponent { } | |
extension PrintLoggerComponent { | |
static func createLogger() -> Logger { | |
return PrintLogger() | |
} | |
} | |
protocol HardcodedSocialServiceComponent: SocialServiceComponent { } | |
extension HardcodedSocialServiceComponent where Self: LoggerComponent { | |
static func createSocialService() -> SocialService { | |
return HardcodedSocialService(logger: logger) | |
} | |
} | |
class Context: PrintLoggerComponent, HardcodedSocialServiceComponent { | |
static let logger = createLogger() | |
static let socialService = createSocialService() | |
} | |
let socialService = Context.socialService | |
socialService.fetchFollowers { (followers) in | |
print(followers) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment