Last active
August 22, 2018 02:48
-
-
Save bramz/b1231a9cd5db4748a066796455143a0c to your computer and use it in GitHub Desktop.
Command handling dependency injection
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 cmd | |
import "fmt" | |
type Cmd struct { | |
trigger string | |
handler CmdHandler | |
} | |
type CmdHandler interface { | |
Name() string // return a string describing command name | |
Register(string) []byte // Register a command by name | |
} | |
func NewCmd(ch CmdHandler) *Cmd { | |
return &Cmd { | |
trigger: []byte("Trigger for command " + ch.Name), | |
handler: ch, | |
} | |
} | |
func (c *Cmd) Register(name string) { | |
c.trigger = c.handler.Register(name) | |
} |
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
type Commands struct { | |
cmds map[string][]byte | |
} | |
func NewCommand() *Commands { | |
return &Commands { | |
cmds: map[string][byte]{}, | |
} | |
} | |
func (c *Commands) Register(name string, handler []byte) { | |
c.cmds[name] = handler | |
} | |
func (c *Commands) Name() string { | |
return "Command" | |
} |
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
func main() { | |
theo := NewCommand() | |
cmd := NewCmd(theo) | |
cmd.handler.Register("theo command") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment