Skip to content

Instantly share code, notes, and snippets.

@LH17
Created January 1, 2019 15:22
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 LH17/0d97f51440bba5d736eceb7967408699 to your computer and use it in GitHub Desktop.
Save LH17/0d97f51440bba5d736eceb7967408699 to your computer and use it in GitHub Desktop.
Strategy Design Pattern
protocol Strategy {
func convert(number: Int)
}
class Convert {
var strategy: Strategy
var number: Int
init(number: Int, strategy: Strategy) {
self.number = number
self.strategy = strategy
}
func update() {
self.strategy.convert(number: number)
}
}
class BinaryStrategy: Strategy {
func convert(number: Int) {
let binary = String(number, radix: 2)
print("Binary is \(binary)")
}
}
class HexStrategy: Strategy {
func convert(number: Int) {
let hex = String(number, radix: 16)
print("Hex is \(hex)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment