Last active
December 6, 2018 05:15
-
-
Save sorin-ref/a33f73f764b40a48f9c6ce01a4423ac0 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
/// 5. All-in-one service solution, supporting: inheritance, functional programming, delegate, default implementation. | |
open class Service5 { | |
public init() { } | |
public var inputFunction: InputFunction? | |
public var outputFunction: OutputFunction? | |
public weak var delegate: Service5Delegate? | |
open func input() -> Bool { | |
return inputFunction?() ?? delegate?.input() ?? false | |
} | |
open func output(text: String) { | |
if let outputFunction = outputFunction { | |
outputFunction(text) | |
} | |
else if let delegate = delegate { | |
delegate.output(text: text) | |
} else { | |
print(type(of: self), text) | |
} | |
} | |
public func doSomething() { | |
if input() { | |
output(text: "done") | |
} | |
} | |
} | |
public typealias InputFunction = () -> Bool | |
public typealias OutputFunction = (String) -> Void | |
public protocol Service5Delegate: class { | |
func input() -> Bool | |
func output(text: String) | |
} | |
public extension Service5Delegate { | |
func output(text: String) -> Void { | |
print(type(of: self), text) | |
} | |
} | |
// Inheritance | |
class Client5a: Service5 { | |
override func input() -> Bool { | |
return true | |
} | |
} | |
Client5a().doSomething() // prints "Client5a done" | |
// Functional programming | |
class Client5b { | |
var input = true | |
var service5 = Service5() | |
init() { | |
service5.inputFunction = { [unowned self] in | |
return self.input | |
} | |
} | |
func doSomething() { | |
service5.doSomething() | |
} | |
} | |
Client5b().doSomething() // prints "Service5 done" | |
// Delegate | |
class Client5c: Service5Delegate { | |
var service5 = Service5() | |
init() { | |
service5.delegate = self | |
} | |
func input() -> Bool { | |
return true | |
} | |
func doSomething() { | |
service5.doSomething() | |
} | |
} | |
Client5c().doSomething() // prints "Client5c done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment