Skip to content

Instantly share code, notes, and snippets.

@riston
Created February 27, 2016 16:37
Show Gist options
  • Save riston/d9957036a59a9df22e09 to your computer and use it in GitHub Desktop.
Save riston/d9957036a59a9df22e09 to your computer and use it in GitHub Desktop.
Simple command pattern in Go lang
package main
import "fmt"
type Command interface {
Execute() string
}
type PingCommand struct{}
func (p *PingCommand) Execute() string {
return "react pings"
}
type StatusCommand struct{}
func (p *StatusCommand) Execute() string {
return "status command"
}
func execByName(name string) string {
// Register commands
commands := map[string]Command{
"ping": &PingCommand{},
"status": &StatusCommand{},
}
if command := commands[name]; command == nil {
return "No such command found, throw error?"
} else {
return command.Execute()
}
}
func main() {
fmt.Println(execByName("status"))
fmt.Println(execByName("ping"))
fmt.Println(execByName("unkown"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment