Skip to content

Instantly share code, notes, and snippets.

@RommelTJ
Created January 30, 2017 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RommelTJ/92368391d0a3c8cb6fd82e6538ae75b0 to your computer and use it in GitHub Desktop.
Save RommelTJ/92368391d0a3c8cb6fd82e6538ae75b0 to your computer and use it in GitHub Desktop.
protocol MyProtocol {
func doSomething() -> String
// factory
static func make() -> MyProtocol
}
typealias WidgetFactory = () -> MyProtocol
class WidgetA: MyProtocol {
func doSomething() -> String {
return "Doing the Widget A stuff"
}
// Factory
static func make() -> MyProtocol {
return WidgetA()
}
}
class WidgetB: MyProtocol {
func doSomething() -> String {
return "Doing the Widget B stuff"
}
// Factory
static func make() -> MyProtocol {
return WidgetB()
}
}
enum WidgetType {
case typeA, typeB
}
enum WidgetHelper {
static func factory(for type: WidgetType) -> WidgetFactory {
switch type {
case .typeA:
return WidgetA.make
case .typeB:
return WidgetB.make
}
}
}
var factory = WidgetHelper.factory(for: .typeA)
var myWidget = factory()
myWidget.doSomething() // Widget does the Widget A stuff
factory = WidgetHelper.factory(for: .typeB)
myWidget = factory()
myWidget.doSomething() // Widget does the Widget B stuff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment