Created
May 6, 2017 20:57
-
-
Save jbehrens94/522e2c390af823f4947b3e5d5ee58de8 to your computer and use it in GitHub Desktop.
FactoryExample
This file contains hidden or 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 | |
// All views implement this protocol. | |
protocol CustomView { | |
func render() -> String | |
} | |
// When no parameters are supplied | |
// let's return this empty view. | |
class EmptyView: CustomView { | |
func render() -> String { | |
return "" | |
} | |
} | |
// When > 0 parameters, let's return this view. | |
class FilledView: CustomView { | |
var strings: [String]! | |
// We instantiate with the parameters, because they aren't empty, | |
// we can assume them able to be explicitly unwrapped. | |
init(_ parameters: [String]) { | |
self.strings = parameters | |
} | |
// Just simply spit out all strings with a new-line. | |
func render() -> String { | |
var finalString = "" | |
strings.forEach { finalString.append("\($0)\n") } | |
return finalString | |
} | |
} | |
// Our factory with static ::make() method. | |
// It simply checks the parameters and then returns either | |
// a FilledView() or an EmptyView(). | |
class ViewFactory { | |
static func make(_ parameters: [String]) -> CustomView? { | |
return parameters.count > 0 ? FilledView(parameters) : EmptyView() | |
} | |
} | |
// parameters.count == 0, no filled view. | |
let parameters = [String]() | |
let emptyView = ViewFactory.make(parameters) | |
emptyView?.render() // returns an empty string. | |
// parameters.count > 0, a filled view. | |
let newParameters = ["This is a string", "This is another one"] | |
let filledView = ViewFactory.make(newParameters) | |
filledView?.render() // returns a string of all of the passed in strings. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment