是否可以使用 Queue of Action 委托来实现 GOF 命令模式?
一段时间以来,我一直试图绕开它,但我很困惑,因为我想添加到队列中的每个可能的操作都可能有不同数量的参数。
有什么建议么?我是否通过专注于命令模式来找出错误的树?
更新:
非常感谢 jgauffin,它很有效......我的实现现在看起来像
public class CommandDispatcher
{
private readonly Dictionary<Type, List<Action<ICommand>>> _registeredCommands =
new Dictionary<Type, List<Action<ICommand>>>();
public void RegisterCommand<T>(Action<ICommand> action) where T : ICommand
{
if (_registeredCommands.ContainsKey(typeof (T)))
_registeredCommands[typeof (T)].Add(action);
else
_registeredCommands.Add(typeof (T), new List<Action<ICommand>> {action});
}
public void Trigger<T>(T command) where T : ICommand
{
if (!_registeredCommands.ContainsKey(typeof(T)))
throw new InvalidOperationException("There are no subscribers for that command");
foreach (var registeredCommand in _registeredCommands[typeof(T)])
{
registeredCommand(command);
if (command.Cancel) break;
}
}
}