Created
April 25, 2019 22:12
-
-
Save richimf/45f56112bcca947a239570667ad828f0 to your computer and use it in GitHub Desktop.
Strategy Pattern in Swift
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
import UIKit | |
/* | |
What: | |
A protocol that defines the action we want to encapsulate. | |
Who: | |
An object who contains an object who conforms the strategy. | |
How: | |
Specific implementation of the strategy. Each implementation is different. | |
*/ | |
// What | |
protocol LoggerStrategy { | |
func log(_ message: String) | |
} | |
// Who | |
struct Logger { | |
let strategy: LoggerStrategy | |
func log(_ message: String){ | |
strategy.log(message) | |
} | |
} | |
// How | |
struct LowerCaseStrategy: LoggerStrategy { | |
func log(_ message: String) { | |
print(message.lowercased()) | |
} | |
} | |
struct UpperCaseStrategy: LoggerStrategy { | |
func log(_ message: String) { | |
print(message.uppercased()) | |
} | |
} | |
let lg1 = Logger(strategy: LowerCaseStrategy()) | |
lg1.log("HELLO strategy") | |
let lg2 = Logger(strategy: UpperCaseStrategy()) | |
lg2.log("Hello another strategy") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment