我已经创建了一个用于执行操作的类,但是我应该在这里实际使用哪种可扩展设计模式

本文关键字:在这里 我应该 可扩展 设计模式 创建 执行 操作 用于 一个 | 更新日期: 2023-09-27 18:14:27

我创建了一个可以通过字符串代码执行方法的类(这是我实际上想要的,因为(已经存在)数据库包含这些代码。然而,我希望这是更可扩展的,因为我添加更多的数据库记录。现在我们必须为每个代码创建一个方法,但我想使用一个接口和一个类,可以在不编辑这个类的情况下创建。你们有什么建议吗?

   public class SpecificAction
    {
    public ActionToPerform ActionToPerform { get; private set; }        
    public string Action { get { return ActionToPerform.Action.Code; } }

    public SpecificAction(ActionToPerform actionToPerform)
    {
        ActionToPerform = actionToPerform;
    }
    public dynamic Execute(object[] parametersArray = null)
    {
        Type type = typeof (SpecificAction);
        MethodInfo methodInfo = type.GetMethod(Action);
        dynamic result = null;
        if (methodInfo != null)
        {
            ParameterInfo[] parameters = methodInfo.GetParameters();
            result = methodInfo.Invoke(this, parameters.Length == 0 ? null : parametersArray);
        }
        return result != null && result;
    }
    //"Restart" is one of the codes in the database
    public bool Restart()
    {
        throw new NotImplementedException();
    }
    //"AddToEventLog" is one of the codes in the database
    public bool AddToEventLog()
    {
        if (!EventLog.SourceExists("Actions"))
        {
            EventLog.CreateEventSource("Actions", "Application");
        }
        EventLog.WriteEntry("Actions", Action + "is executed", EventLogEntryType.Warning);
        return true;
    }
    //"SendEmail" is one of the codes in the database
    public bool SendEmail()
    {
        throw new NotImplementedException();
    }
}

我这样调用它,它可以工作:

        bool isPerformed = false;
        var action = new SpecificAction(actionToPerform);
        isPerformed = action.Execute();

然而,我会发现它的方式更好地实现一个类的每个可能的动作和动态执行一个方法在那里,这是可能的一些现有的模式,你能给我一个例子,因为我已经尝试了很多?

我已经创建了一个用于执行操作的类,但是我应该在这里实际使用哪种可扩展设计模式

通常这类问题可以使用命令模式来解决。

命令模式"封装了以后调用方法所需的所有信息"。

关于命令模式的更多信息。

Command模式通常使用一个抽象基类(或接口)Command,我们从中构建命令的继承层次结构。通过这种方式,我们不需要确切地知道运行时将执行什么命令,只需要知道调用它所需的接口。