设计模式——命令模式

命令模式:将“请求”封装成对象,以便使用不同的请求、队列或者日志来参数化其他对象。命令模式也支持可撤销的操作。

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()
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值