From 06577bacec810939f965a1f5efaa3e37da9f2b4b Mon Sep 17 00:00:00 2001
From: Edward <crazybber@outlook.com>
Date: Tue, 5 May 2020 22:24:15 +0800
Subject: [PATCH] add a command pattern example

---
 behavior/11_command/command_draw.go | 56 +++++++++++++++++++++++++++++
 behavior/11_command/command_test.go | 21 +++++++++++
 2 files changed, 77 insertions(+)
 create mode 100644 behavior/11_command/command_draw.go

diff --git a/behavior/11_command/command_draw.go b/behavior/11_command/command_draw.go
new file mode 100644
index 0000000..992f9e4
--- /dev/null
+++ b/behavior/11_command/command_draw.go
@@ -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)
+}
diff --git a/behavior/11_command/command_test.go b/behavior/11_command/command_test.go
index 7e080d5..f487193 100644
--- a/behavior/11_command/command_test.go
+++ b/behavior/11_command/command_test.go
@@ -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())
+	}
+
+}