add a command pattern example

This commit is contained in:
Edward 2020-05-05 22:24:15 +08:00
parent 20b48391b3
commit 06577bacec
2 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,56 @@
package command
import (
"strconv"
)
type command interface {
Execute() string
}
//PathPainter invoke an draw command
type PathPainter struct {
commands []command
}
//Execute run cmd
func (p *PathPainter) Execute() string {
var result string
for _, command := range p.commands {
result += command.Execute() + "\n"
}
return result
}
//Append new cmd PathPainter
func (p *PathPainter) Append(command command) {
p.commands = append(p.commands, command)
}
//Undo last step cmd
func (p *PathPainter) Undo() {
if len(p.commands) != 0 {
p.commands = p.commands[:len(p.commands)-1]
}
}
//Clear all
func (p *PathPainter) Clear() {
p.commands = []command{}
}
//Position pos
type Position struct {
X, Y int
}
//DrawCommand 命令执行者
//DrawCommand line to
type DrawCommand struct {
Position *Position
}
//Execute cmd
func (d *DrawCommand) Execute() string {
return strconv.Itoa(d.Position.X) + "." + strconv.Itoa(d.Position.Y)
}

View File

@ -32,3 +32,24 @@ func TestTroopCommand(t *testing.T) {
in.Execute()
}
func TestDrawCommand(t *testing.T) {
painter := PathPainter{}
painter.Append(&DrawCommand{&Position{1, 1}})
painter.Append(&DrawCommand{&Position{2, 2}})
painter.Append(&DrawCommand{&Position{1, 3}})
expect := "1.1\n2.2\n1.3\n"
if painter.Execute() != expect {
t.Errorf("Expect result to equal %s, but %s.\n", expect, painter.Execute())
}
painter.Undo()
expect = "1.1\n2.2\n"
if painter.Execute() != expect {
t.Errorf("Expect result to equal %s, but %s.\n", expect, painter.Execute())
}
}