forked from QianMo/Unity-Design-Pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandPatternExample4.cs
More file actions
136 lines (110 loc) · 2.98 KB
/
Copy pathCommandPatternExample4.cs
File metadata and controls
136 lines (110 loc) · 2.98 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
//-------------------------------------------------------------------------------------
// CommandPatternExample4.cs
//-------------------------------------------------------------------------------------
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace CommandPatternExample4
{
public class CommandPatternExample4 : MonoBehaviour
{
void Start()
{
Invoker theInvoker = new Invoker();
Command theCommand = null;
// 结合命令与执行者
theCommand = new ConcreteCommand1(new Receiver1(), "hi");
theInvoker.AddCommand(theCommand);
theCommand = new ConcreteCommand2(new Receiver2(), 666);
theInvoker.AddCommand(theCommand);
// 进行执行
theInvoker.ExecuteCommand();
}
}
/// <summary>
/// 命令抽象类
/// </summary>
public abstract class Command
{
public abstract void Execute();
}
/// <summary>
/// 实际命令1-绑定命令和receiver
/// </summary>
public class ConcreteCommand1 : Command
{
Receiver1 m_Receiver = null;
string m_Command = "";
public ConcreteCommand1(Receiver1 Receiver, string param)
{
m_Receiver = Receiver;
m_Command = param;
}
public override void Execute()
{
m_Receiver.Action(m_Command);
}
}
/// <summary>
/// 实际命令2-绑定命令和receiver
/// </summary>
public class ConcreteCommand2 : Command
{
Receiver2 m_Receiver = null;
int m_Param = 0;
public ConcreteCommand2(Receiver2 Receiver, int Param)
{
m_Receiver = Receiver;
m_Param = Param;
}
public override void Execute()
{
m_Receiver.Action(m_Param);
}
}
/// <summary>
/// 功能执行者1
/// </summary>
public class Receiver1
{
public Receiver1() { }
public void Action(string param)
{
Debug.Log("Receiver1.Action:Command[" + param + "]");
}
}
/// <summary>
/// 功能执行者2
/// </summary>
public class Receiver2
{
public Receiver2() { }
public void Action(int Param)
{
Debug.Log("Receiver2.Action:Param[" + Param.ToString() + "]");
}
}
/// <summary>
/// 命令管理者
/// </summary>
public class Invoker
{
List<Command> m_Commands = new List<Command>();
// 加入命令
public void AddCommand(Command theCommand)
{
m_Commands.Add(theCommand);
}
/// <summary>
/// 执行命令
/// </summary>
public void ExecuteCommand()
{
// 执行
foreach (Command theCommand in m_Commands)
theCommand.Execute();
// 清空
m_Commands.Clear();
}
}
}