mirror of
https://github.com/crazybber/go-pattern-examples.git
synced 2024-11-21 19:36:03 +03:00
add a command pattern example
This commit is contained in:
parent
20b48391b3
commit
06577bacec
56
behavior/11_command/command_draw.go
Normal file
56
behavior/11_command/command_draw.go
Normal 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)
|
||||
}
|
@ -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())
|
||||
}
|
||||
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user