Skip to content

Instantly share code, notes, and snippets.

@rintaro
Last active May 19, 2017 07:46
Show Gist options
  • Save rintaro/b16f05411cfe540754285dcc0da60174 to your computer and use it in GitHub Desktop.
Save rintaro/b16f05411cfe540754285dcc0da60174 to your computer and use it in GitHub Desktop.
protocol Factory {
init(factory: () -> Self)
}
extension Factory {
init(factory: () -> Self) {
self = factory()
}
}
class Animal {
var emoji: Character { return "❓" }
}
class Cat : Animal {
override var emoji: Character { return "🐱" }
}
class Dog : Animal {
override var emoji: Character { return "🐶" }
}
extension Animal : Factory {
convenience init(type: String) {
self.init(factory: {
switch type {
case "dog": return Dog()
case "cat": return Cat()
default: return Animal()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment