将一个请求封装为一个对象,从而使我们可用不同的请求对客户进行参数化;对请求排队或者记录请求日志,以及支持可撤销的操作。
- 将命令作为成员函数封装到对应的命令对象中,然后在box内通过interface数组或者成员变量指向命令对象的实例实现对命令的封装。
![](https://img.haomeiwen.com/i4559317/edd507ad3957abbb.png)
package main
import "fmt"
//命令抽象接口
type Command interface {
Execute()
}
type StartCommand struct {
}
func (c *StartCommand) Execute() {
fmt.Println("Command call by StartCommand")
}
type CloseCommand struct {
}
func (c *CloseCommand) Execute() {
fmt.Println("Command call by CloseCommand")
}
//请求结构体
type Box struct {
button1 Command
button2 Command
}
//抽象请求对象
func NewBox(button1, button2 Command) *Box {
return &Box{
button1: button1,
button2: button2,
}
}
//封装命令执行函数
func (b *Box) Pressbutton1() {
b.button1.Execute()
}
//封装命令执行函数
func (b *Box) Pressbutton2() {
b.button2.Execute()
}
func main() {
button1 := new(StartCommand)
button2 := new(CloseCommand)
newbox := NewBox(button1, button2)
newbox.Pressbutton1()
newbox.Pressbutton2()
}
网友评论