Go Example
package main
type button struct {
command command
}
func (b *button) press() {
b.command.execute()
}
package main
type command interface {
execute()
}
package main
type device interface {
on()
off()
}
package main
type offCommand struct {
device device
}
func (c *offCommand) execute() {
c.device.off()
}
package main
type onCommand struct {
device device
}
func (c *onCommand) execute() {
c.device.on()
}
package main
import "fmt"
type tv struct {
isRunning bool
}
func (t *tv) on() {
t.isRunning = true
fmt.Println("Turning tv on")
}
func (t *tv) off() {
t.isRunning = false
fmt.Println("Turning tv off")
}
package main
func main() {
tv := &tv{}
onCommand := &onCommand{
device: tv,
}
offCommand := &offCommand{
device: tv,
}
onButton := &button{
command: onCommand,
}
onButton.press()
offButton := &button{
command: offCommand,
}
offButton.press()
}
Turning tv on
Turning tv off