Created
December 7, 2015 03:30
-
-
Save rileytestut/0e6e80d3f22b845502e7 to your computer and use it in GitHub Desktop.
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
//: Playground - noun: a place where people can play | |
import Foundation | |
enum GameSystemIdentifier | |
{ | |
case Wii | |
case Xbox | |
case PlayStation | |
} | |
struct Game | |
{ | |
let name: String | |
let URL: NSURL | |
let gameSystemIdentifier: GameSystemIdentifier | |
} | |
// Abstract class | |
// Handles receiving a Game struct, and then can "play" the game | |
// Because each system is different, there are specialized subclasses intended to each handle a specific system | |
class GameSystem | |
{ | |
// This method is invoked whenever GameSystem(game: game) is called to determine what subclass should be initialized | |
// The return type should (theoretically) be of type GameSystem.Type, but alas that is currently a compile-time error | |
class func dynamicTypeForInitializationParameters(parameters: [String: AnyObject]) -> AnyObject.Type /* GameSystem.Type */ | |
{ | |
// The `parameters` dictionary maps strings representing the initializer parameter names to the provided values | |
// In this case, "game" maps to an instance of Game | |
guard let game = parameters["game"] as? Game else { return GameSystem.self } | |
switch game.gameSystemIdentifier | |
{ | |
case .Wii: return WiiGameSystem.self | |
case .Xbox: return XboxGameSystem.self | |
case .PlayStation: return PlaystationGameSystem.self | |
} | |
} | |
init(game: Game) | |
{ | |
// Initialize as normal | |
} | |
} | |
// "Private" implementation subclasses, specialized for handling games made for that specific system | |
class WiiGameSystem { } | |
class XboxGameSystem { } | |
class PlaystationGameSystem { } | |
// In practice, the gameSystemIdentifier would be determined dynamically by reading the UTI of the file at URL | |
let game = Game(name: "Pokemon", URL: NSURL(string: "path/to/game")!, gameSystemIdentifier: .Wii) | |
// Caller has no need to know exactly what GameSystem will be used to run the game | |
// This is great if the framework separates each GameSystem into a separate module, and could add more later on | |
let gameSystem = GameSystem(game: game) | |
// In theory, this would print "WiiGameSystem" | |
print(gameSystem.dynamicType) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment