在命令模式c#中为单个命令添加更多方法

时间:2016-10-03 12:35:43

标签: c# oop command-pattern

我使用Command Design Pattern在我的简单应用程序中创建菜单。

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

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

2 个答案:

答案 0 :(得分:2)

命令存在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原则并使代码更复杂。

答案 1 :(得分:0)

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

相关问题