命令模式
2019-01-31 本文已影响0人
bocsoft
1、定义:对于“行为请求者”和“行为实现者”,将一组行为抽象为对象,实现二者的松耦合.命令可以提供撤销操作
2、角色:
Command:抽象命令接口.
ConcreteCommand:具体命令.
Receiver:最终执行命令的对象.
Invoker:命令对象的入口.
Go 实现版本
package command
import "strconv"
/*
1、定义:对于“行为请求者”和“行为实现者”,将一组行为抽象为对象,实现二者的松耦合.命令可以提供撤销操作
2、角色:
Command:抽象命令接口.
ConcreteCommand:具体命令.
Receiver:最终执行命令的对象.
Invoker:命令对象的入口.
*/
//命令接口
type command interface {
Execute() string
}
//命令组
type MacroCommand struct {
commands []command
}
// 实现命令执行逻辑
func (self *MacroCommand) Execute() string {
var result string
for _, command := range self.commands {
result += command.Execute() + "\n"
}
return result
}
//增加命令
func (self *MacroCommand) Append(command command) {
self.commands = append(self.commands, command)
}
//撤销操作
func (self *MacroCommand) Undo() {
if len(self.commands) != 0 {
self.commands = self.commands[:len(self.commands)-1]
}
}
//清空命令
func (self *MacroCommand) Clear() {
self.commands = []command{}
}
type Position struct {
X, Y int
}
//创建具体命令对象
type DrawCommand struct {
Position *Position
}
func (self *DrawCommand) Execute() string {
return strconv.Itoa(self.Position.X) + "." + strconv.Itoa(self.Position.Y)
}
package command
import (
"testing"
)
func TestCommand(t *testing.T){
macro := MacroCommand{}//创建命令组
//向命令组中增加命令
macro.Append(&DrawCommand{&Position{1, 1}})
macro.Append(&DrawCommand{&Position{2, 2}})
expect := "1.1\n2.2\n"
if macro.Execute() != expect {
t.Errorf("Expect result to equal %s, but %s.\n", expect, macro.Execute())
}
//撤销一个命令
macro.Undo()
expect = "1.1\n"
if macro.Execute() != expect {
t.Errorf("Expect result to equal %s, but %s.\n", expect, macro.Execute())
}
}