Skip to content

Instantly share code, notes, and snippets.

@kien-hoang
Last active January 11, 2023 16:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kien-hoang/5871f7c3f87980881680e08f84ed174d to your computer and use it in GitHub Desktop.
Save kien-hoang/5871f7c3f87980881680e08f84ed174d to your computer and use it in GitHub Desktop.
protocol Strategy {
func execute(a: Int, b: Int)
}
class ConcreteStrategyAdd: Strategy {
func execute(a: Int, b: Int) {
print("a + b = \(a + b)")
}
}
class ConcreteStrategySubtract: Strategy {
func execute(a: Int, b: Int) {
print("a - b = \(a - b)")
}
}
class ConcreteStrategyMultiply: Strategy {
func execute(a: Int, b: Int) {
print("a * b = \(a * b)")
}
}
class Context {
private var strategy: Strategy?
func setStrategy(_ strategy: Strategy) {
self.strategy = strategy
}
func executeStrategy(a: Int, b: Int) {
strategy?.execute(a: a, b: b)
}
}
let context = Context()
context.setStrategy(ConcreteStrategyAdd())
context.executeStrategy(a: 10, b: 5) // a + b = 15
context.setStrategy(ConcreteStrategySubtract())
context.executeStrategy(a: 10, b: 5) // a - b = 5
context.setStrategy(ConcreteStrategyMultiply())
context.executeStrategy(a: 10, b: 5) // a * b = 50
// Reference:
// [Dive Into Design Pattern - Alexander Shvets](https://refactoring.guru/design-patterns/book)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment