go 示例

最后更新于:2022-04-02 04:20:43

[TOC] ## 示例 ### 电视开关
main.go ``` package main import "fmt" // 接收者接口 type device interface { on() off() } // 命令接口 type command interface { execute() } // 具体接口 type onCommand struct { device device } func (c *onCommand) execute() { c.device.on() } // 具体接口 type offCommand struct { device device } func (c *offCommand) execute() { c.device.off() } // 请求者 type button struct { command command } func (b *button) press() { b.command.execute() } 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") } func main() { tv := &tv{} onCommand := &onCommand{ device: tv, } onButton := &button{ command: onCommand, } onButton.press() offCommand := &offCommand{ device: tv, } offButton := &button{ command: offCommand, } offButton.press() } ```

输出 ``` Turning tv on Turning tv off ```
';