Created
January 30, 2017 00:46
-
-
Save RommelTJ/92368391d0a3c8cb6fd82e6538ae75b0 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
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