Skip to content

Instantly share code, notes, and snippets.

@LH17
Created January 1, 2019 14:43
Show Gist options
  • Save LH17/a49cbaf298f7838ebd10a1711c78bcc5 to your computer and use it in GitHub Desktop.
Save LH17/a49cbaf298f7838ebd10a1711c78bcc5 to your computer and use it in GitHub Desktop.
Command Design Pattern
protocol Command {
func execute()
}
class ConcreteCommand: Command {
var colorReceiver: ColorReceiver
init(colorReceiver: ColorReceiver) {
self.colorReceiver = colorReceiver
}
func execute() {
colorReceiver.changeColor()
}
}
class Invoker {
func execute(command: Command) {
command.execute()
}
}
class ColorReceiver {
var color: Color
init(color: Color) {
self.color = color
}
func changeColor() {
print(color.name)
}
}
struct Color {
var name: String
}
class Client {
let invoker = Invoker()
func showPattern() {
let colorReceiver = ColorReceiver(color: Color(name: "red"))
let command: Command = ConcreteCommand(colorReceiver: colorReceiver)
invoker.execute(command: command)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment