Last active
January 11, 2023 16:44
-
-
Save kien-hoang/5871f7c3f87980881680e08f84ed174d 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
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