Last active
April 17, 2017 22:56
-
-
Save ahcode0919/569d82560de71213999f93f0dc9ef7bc to your computer and use it in GitHub Desktop.
Example of the factory pattern in Swift
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
//Factory Pattern (Creational) | |
//Allows logic of which type will be created to be handled by a method | |
protocol SimpleType { | |
var simpleName: String { get } | |
} | |
struct Type1: SimpleType { | |
var simpleName: String = "Type1" | |
} | |
struct Type2: SimpleType { | |
var simpleName: String = "Type2" | |
} | |
/* | |
Factory Method | |
Handles logic of which specific struct to return | |
*/ | |
func simpleTypeFactory(getType type: Int) -> SimpleType? { | |
switch type { | |
case 1: | |
return Type1() | |
case 2: | |
return Type2() | |
default: | |
return nil | |
} | |
} | |
let type1 = simpleTypeFactory(getType: 1) | |
type1?.dynamicType //Type1 | |
type1?.simpleName //"Type1" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment