【问题标题】:Adding more methods to single command in command pattern c#在命令模式c#中向单个命令添加更多方法
【发布时间】:2016-10-03 12:35:43
【问题描述】:

我使用命令设计模式在我的简单应用程序中创建菜单。

interface ICommand
{
    string Description { get; }
    void Execute(Library books, List<Book> bookList);
    bool ValueChecker(string checkValue);
}

我正在使用 ValueChecker 检查我的答案中的字段是否仅为 int 并且有些独特。 (我在 AddBookCommand 类中添加产品)。向接口添加更多方法(如bool IsUniquebool IsYearLessThanCurrent)会是一种不好的做法,还是我应该考虑其他方法在我的菜单中进行一些简单的错误处理?

【问题讨论】:

  • 我认为你不应该在你的命令中加入太多的逻辑。命令应该是愚蠢的。相反,您应该创建处理您的命令的命令处理程序。其中一些可能是验证者。然后你建立一个处理程序链并将你的命令传递给链。如果它通过了验证器,那么您将继续执行。如果没有,你就做别的事情。
  • @JakubRusilko 你能告诉我一些这样的处理程序的简短样本吗?我是编码的新手。
  • 很难为您提供一个适合您的特定情况的全面示例,@Easy。不过网上有很多关于命令等的文章,我可以推荐这个网站:sourcemaking.com/design_patterns。查看本页描述的命令模式和责任链模式。

标签: c# oop command-pattern


【解决方案1】:

命令存在有 1 个原因 = 执行一些逻辑。有时允许添加有关撤消功能或逻辑的逻辑,这决定了现在是否可以使用此命令。 .NET中已经定义了这个接口here

///<summary>
///     An interface that allows an application author to define a method to be invoked.
///</summary>
public interface ICommand
{
    /// <summary>
    ///     Raised when the ability of the command to execute has changed.
    /// </summary>
    event EventHandler CanExecuteChanged;

    /// <summary>
    ///     Returns whether the command can be executed.
    /// </summary>
    /// <param name="parameter">A parameter that may be used in executing the command. This parameter may be ignored by some implementations.</param>
    /// <returns>true if the command can be executed with the given parameter and current state. false otherwise.</returns>
    bool CanExecute(object parameter);

    /// <summary>
    ///     Defines the method that should be executed when the command is executed.
    /// </summary>
    /// <param name="parameter">A parameter that may be used in executing the command. This parameter may be ignored by some implementations.</param>
    void Execute(object parameter);
}

在这里为您的对象添加额外的逻辑并不好。它打破了SRP的原则,使代码更加复杂。

【讨论】:

    【解决方案2】:

    是的,你可以,但如果你尽可能保持 Icommand 通用,它会更有效。您还可以定义一个 IcommandBase,它将保留所有执行和所有这些通用方法。然后定义另一个 Icommand 说 IcommandBook 专门用于您的对象,如 Books 和 Student。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-19
      • 2010-11-23
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多