Skip to content

Instantly share code, notes, and snippets.

@podratz
Last active April 18, 2025 16:39
Show Gist options
  • Save podratz/8d65c5307e9bfaf63fb2b3674e46a729 to your computer and use it in GitHub Desktop.
Save podratz/8d65c5307e9bfaf63fb2b3674e46a729 to your computer and use it in GitHub Desktop.
Strategy Selector
class StrategySelector {
private var strategy: (() -> Void)!
private var state: String = ""
init() {
strategy = strategyA
}
func execute() {
strategy()
}
func read() -> String {
state
}
func selectStrategyA() {
strategy = strategyA
}
func selectStrategyB() {
strategy = strategyB
}
private func strategyA() {
state.append("A")
}
private func strategyB() {
state.append("B")
}
}
let selector = StrategySelector()
selector.execute()
selector.selectStrategyB()
selector.execute()
selector.selectStrategyA()
selector.execute()
selector.execute()
selector.read() // ABAA
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment