Skip to content

Instantly share code, notes, and snippets.

@richimf
Created April 25, 2019 22:12
Show Gist options
  • Save richimf/45f56112bcca947a239570667ad828f0 to your computer and use it in GitHub Desktop.
Save richimf/45f56112bcca947a239570667ad828f0 to your computer and use it in GitHub Desktop.
Strategy Pattern in Swift
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