【问题标题】:Implementing the Command Pattern using C# Action delegate使用 C# 动作委托实现命令模式
【发布时间】:2011-04-23 15:46:39
【问题描述】:

是否可以使用 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;
        }
    }
}

【问题讨论】:

    标签: c# design-patterns delegates command-pattern


    【解决方案1】:

    如果您关心参数的数量,那么使用类正确实现命令模式将是正确的方法。 Action 代表仅限于一个。此外,如果您使用 Action 委托,您可能希望稍后实现撤消,因为您只是使用委托而不是类,因此您将无法执行此操作。

    【讨论】:

      【解决方案2】:

      您可以使用操作。您不应使用多个参数。如果命令需要一个新参数会发生什么?然后您需要更改调用命令和处理程序的所有位置。

      相反,您应该使用具有所有参数作为属性的命令类。这样你就可以在不影响代码的情况下添加参数(新参数在处理程序中应该被视为可选)。

      我会这样做:

      public interface ICommand
      {
          // Cancel processing, do not invoke any more handlers
          public bool Cancel { get; set; }
      }
      
      public class CommandDispatcher 
      {
        private Dictionary<Type, List<Action<ICommand>>> _commands = new Dictionary<Type, List<Action<ICommand>>>();
      
      
        // Add to dictionary here
        public void Subscribe<T>(Action<T> action) where T : ICommand
        {
            List<Action<ICommand>> subscribers;
            if (!_commands.TryGetValue(typeof(T), out subscribers))
            {
                subscribers = new List<Action<ICommand>>();
                _commands.Add(typeof(T), subscribers));
            }
      
            subscribers.Add(action);
        }
      
        // find command and to foreach to execute the actions      
        public void Trigger<T>(T command) where T : ICommand
        {
            List<Action<ICommand>> subscribers;
            if (!_commands.TryGetValue(typeof(T), out subscribers))
                throw new InvalidOperationException("There are no subscribers for that command");
      
            foreach(var subsriber in subscribers)
            {
                subscriber(command);
                if (command.Cancel)
                    break; //a handler canceled the command to prevent others from processing it.
            }
        }
      
      }
      
      public class AddTextCommand : ICommand
      {
          public string TextToAdd {get;set;}
      }
      
      public class TextHandler
      {
          public TextHandler(CommandDispatcher dispatcher)
          {
              disptacher.Subscribe<AddTextCommand>(OnAddText);
          }
      
          public void OnAddText(AddTextCommand cmd)
          {
              //....
          }
      }
      
      
      public partial class MyForm : Form
      {
          CommandDispatcher _dispatcher;
      
          private void MyTextBox_Changed(object source, EventArgs e)
          {
              _dispatcher.Trigger(new AddTextCommand{TextToAdd = MyTextBox.Text}=;
          } 
      }
      

      请注意,代码是一种伪代码。我直接在答案中写了它而没有测试它。你可能必须改变一些东西才能让它工作,但它至少应该给你一个提示。该实现让您为每个命令添加多个订阅者。

      【讨论】:

      • 这似乎是一个有趣的解决方案,您介意详细说明触发方法的工作原理吗? command(T) 还是 command.Invoke()?为什么是 _commands 的字典,为什么不只是一个直接的列表或队列?
      • 字典速度更快,你不必自己遍历集合找到正确的命令类型(以及它的订阅者)
      • 我已经添加了实现。他们可能无法 100% 工作。试着让它工作。
      • 如果不想自己实现可以使用我的 Griffin.Decoupled:blog.gauffin.org/2012/10/introducing-griffin-decoupled
      【解决方案3】:

      在命令模式中,典型的命令接口将具有简单的执行方法——这可以用动作委托来表示。但实际实现将由不同的具体类提供,您将/可以在其中传递参数(例如,通过构造函数)。例如:

      public interface ICommand 
      {
         public void Execute();
      }
      
      public class Command1 : ICommand
      {
         public Command1(int param1, string param2)
         {
         }
      
         ...
      }
      
      public class Command2 : ICommand
      {
        ...
      }
      
      public class Program
      {
      
         public static void Main()
         {
      
             ...
      
             var commands = new List<Action>();
             commands.Add((new Command1(3, "Hello")).Execute);
             commands.Add((new Command2(...)).Execute);
      
             ...
         }
      
      
      }
      

      这里的重点是命令相关的状态和实现将被封装在不同的实现中,而动作委托将指向其实例方法。所以调用委托会导致命令的执行。

      【讨论】:

        猜你喜欢
        • 2019-10-07
        • 1970-01-01
        • 1970-01-01
        • 2010-11-04
        • 1970-01-01
        • 2012-04-02
        • 1970-01-01
        • 2021-04-07
        • 2011-01-13
        相关资源
        最近更新 更多