命令模式

这个命令模式确实有点意思,可以将判断与执行解耦,并且可以回退,原因是Commmad记录了操作对象执行命令之前的状态,或者Revock可以给到一个相反的状态

并且文中提到如果使用第一公民函数的语言和闭包也可以实现,重点就是要可以记录状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
public interface BaseCommand
{
/// <summary>
/// 执行命令
/// </summary>
/// <param name="command"></param>
/// <param name="obj"></param>
public void Execute(GameObject gameObject);
/// <summary>
/// 回退命令
/// </summary>
/// <param name="obj"></param>
public void Revoke(GameObject gameObject);
}

public class MoveCommand : BaseCommand
{
private GameObject m_gameObject;
private Vector3 m_direction;

public MoveCommand(Vector3 dir)
{
m_direction = dir;
}

public void Execute(GameObject obj)
{
m_gameObject = obj;
m_gameObject.transform.Translate(m_direction);
}

public void Revoke(GameObject obj)
{
m_gameObject = obj;
m_gameObject.transform.Translate(Quaternion.Euler(0f, 180f, 0f) * m_direction);
}
}

public static class CommandManager
{
private static Stack<BaseCommand> m_commands = new Stack<BaseCommand>();
public static void Clear() { m_commands.Clear(); }
/// <summary>
/// 执行命令
/// </summary>
/// <param name="command"></param>
/// <param name="obj"></param>
public static void Excute(BaseCommand command, GameObject obj)
{
command.Execute(obj);
m_commands.Push(command);
}
/// <summary>
/// 回退命令
/// </summary>
/// <param name="obj"></param>
public static void Revock(GameObject obj)
{
if (m_commands.TryPop(out BaseCommand commmand))
{
commmand.Revoke(obj);
}
}
}

public class TestCommandMode : MonoBehaviour
{
private MoveCommand m_moveForwad;
private MoveCommand m_moveBack;
private MoveCommand m_moveLeft;
private MoveCommand m_moveRight;

private void Start()
{
m_moveForwad = new MoveCommand(Vector3.forward);
m_moveBack = new MoveCommand(Vector3.back);
m_moveLeft = new MoveCommand(Vector3.left);
m_moveRight = new MoveCommand(Vector3.right);
}

private void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
CommandManager.Excute(m_moveForwad, gameObject);
}
if (Input.GetKeyDown(KeyCode.S))
{
CommandManager.Excute(m_moveBack, gameObject);
}
if (Input.GetKeyDown(KeyCode.A))
{
CommandManager.Excute(m_moveLeft, gameObject);
}
if (Input.GetKeyDown(KeyCode.D))
{
CommandManager.Excute(m_moveRight, gameObject);
}
if (Input.GetKeyDown(KeyCode.R))
{
CommandManager.Revock(gameObject);
}
}
}