Created
February 27, 2016 16:37
-
-
Save riston/d9957036a59a9df22e09 to your computer and use it in GitHub Desktop.
Simple command pattern in Go lang
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
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