命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。
package main
import "fmt"
//灯
type Light struct{
room string
}
func (l Light) on(){
fmt.Println(l.room, "light is on")
}
func (l Light) off(){
fmt.Println(l.room, "light is off")
}
/*
1.吊扇高、中、低档可以分为3个命令。
2.遥控器一个按钮执行一组动作:设置命令宏,宏中包含[]Commands,命令宏execute()时会执行这组命令。
*/
//命令接口
type Command interface{
execute()
undo()
}
//无命令
type NoCommand struct{
}
func (NoCommand) execute(){
}
func (NoCommand) undo(){
}
//开灯命令
type LightOnCommand struct{
light Light
}
func (l LightOnCommand) execute(){
l.light.on()
}
func (l LightOnCommand) undo(){
l.light.off()
}
//关灯命令
type LightOffCommand struct{
light Light
}
func (l LightOffCommand) execute(){
l.light.off()
}
func (l LightOffCommand) undo(){
l.light.on()
}
//遥控器
type RemoteControl struct{
onCommands [7]Command
offCommands [7]Command
undoCommand Command
}
func NewRemoteControl() *RemoteControl{
res := &RemoteControl{}
for i:=0;i<7;i++ {
res.onCommands[i] = NoCommand{}
}
for i:=0;i<7;i++ {
res.offCommands[i] = NoCommand{}
}
res.undoCommand = NoCommand{}
return res
}
func(r *RemoteControl) setCommand(slot int, onCommand Command, offCommand Command)(){
r.onCommands[slot] = onCommand
r.offCommands[slot] = offCommand
}
func (r *RemoteControl) onButtonWasPushed(slot int){
r.onCommands[slot].execute()
r.undoCommand = r.onCommands[slot]
}
func (r *RemoteControl) offButtonWasPushed(slot int){
r.offCommands[slot].execute()
r.undoCommand = r.offCommands[slot]
}
func (r RemoteControl) undoButtonWasPushed(){
fmt.Printf("%v",r.undoCommand)
}
func main () {
light := Light{room:"Kitchen"}
lightOnCommand := LightOnCommand{light:light}
lightOffCommand := LightOffCommand{light:light}
remoteControl := NewRemoteControl()
remoteControl.setCommand(0, lightOnCommand, lightOffCommand)
remoteControl.onButtonWasPushed(0)
remoteControl.offButtonWasPushed(0)
remoteControl.undoButtonWasPushed()
}