8

我有一个在数据库中排队的作业列表,我需要从数据库中读取并使用线程并行执行它们,并且我有一个命令类列表来执行所有这些作业,这些作业都实现了一个通用接口(命令模式)。但是当我从数据库中检索待处理的作业时,我需要为每个作业实例化正确的命令对象,就像这样(在工厂类中)

ICommand command;
switch (jobCode)
{
  case "A":
     command = new CommandA();
     break;
  case "B":
     command = new CommandB();
     break;
  case "C":
     command = new CommandC();
     break;
}

command.Execute();

有没有更好的方法来创建正确的命令对象而不使用像上面这样的大 switch 语句?或者是否有任何其他模式可以执行排队的作业?

解决方案:像这样解决(基于选择的答案)。这将对命令对象进行延迟实例化。

public class CommandFactory
{
    private readonly IDictionary<string, Func<ICommand>> _commands;

    public CommandFactory()
    {
        _commands = new Dictionary<string, Func<ICommand>>
                        {
                            {"A", () => new CommandA()},
                            {"B", () => new CommandB()},
                            {"C", () => new CommandC()}
                        };
    }

    public ICommand GetCommand(string jobKey)
    {
        Func<ICommand> command;
        _commands.TryGetValue(jobKey.ToUpper(), out command);
        return command();
    }
}    

Client: 

        var factory = new CommandFactory();
        var command = factory.GetCommand(jobKey);
        command.Execute();
4

3 回答 3

14

大多数 C# 命令模式实现或多或少与 Java 实现相同。这些实现通常使用 ICommand 接口:

public interface ICommand
{
    void Execute();
}

然后强制所有命令类实现接口。我对这个解决方案没有任何问题,但我个人不喜欢创建太多的类,我更喜欢使用 .NET 委托(Java 中没有委托)。如果只需要一个方法引用,Action 委托通常可以解决问题:

public class Prog
{
    public Prog()
    {
        var factory = new CommandFactory();
        factory.Register("A", () => new A().DoA);            
        factory.Register("B", () => new B().DoB);
        factory.Register("C", DoStuff);

        factory.Execute("A");
    }

  public static void DoStuff()
    {
    }
}

public class CommandFactory
{
    private readonly IDictionary<string, Action> _commands;       

    public void Register(string commandName, Action action)
    {
    _commands.Add(commandName, action); 
    }

    public Action GetCommand(string commandName)
    {
        _commands[commandName];
    }

    public void Execute(string commandName)
    {
        GetCommand(commandName)();
    }
}
public class A
{
    public void DoA()
    {
    }
}

public class B
{
    public void DoB()
    {
    }
}

如果您的命令界面需要多个方法,例如:

public interface ICommand
{
    void Execute();
    void Undo();
}

您可以使用这样的包装类:

public class Command
{
    public Command(Action execute, Action undo)
    {
        Execute = execute;
        Undo = undo;
    }

    public Action Execute { get; protected set; }
    public Action Undo { get; protected set; }
}

或(不管是哪一个)

public class Command 
{
    private readonly Action _execute;
    private readonly Action _undo;

    public Command(Action execute, Action undo)
    {
        _execute = execute;
        _undo = undo;
    }

    public void Execute()
    {
        _execute();
    }

    public void Undo()
    { 
        _undo();
    }
}

(如果您已经使用了遗留的东西,这个甚至可以实现 ICommand。如果您使用接口,工厂应该使用接口而不是 Command 类)

使用这样的包装器,您不必为要支持的每个操作创建命令类。以下示例演示了如何使用包装类:

public class Prog2
{
    public Prog2()
    {
        var factory = new CommandFactory2();
        factory.Register("A", new Lazy<Command>(
            ()=>
                {
                    var a = new A();
                    return new Command(a.DoA, a.UndoA);
                }));

        factory.Register("B", new Lazy<Command>(
           () =>
           {
               var c = new B();
               return new Command(c.DoB, c.DoB);
           }));

        factory.Register("C", new Lazy<Command>(
            () => new Command(DoStuff, UndoStuff)));

        factory.Execute("A");
    }

    public static void DoStuff()
    {
    }

    public static void UndoStuff()
    {
    }
}

public class CommandFactory2
{
    private readonly IDictionary<string, Lazy<Command>> _commands;

    public void Register(string commandName, Lazy<Command> lazyCommand)
    {
        _commands.Add(commandName, lazyCommand);
    }

    public void Register(string commandName, Action execute, Action undo)
    {
        _commands.Add(commandName, new Lazy<Command>(() => new Command(execute, undo)));
    }

    public Command GetCommand(string commandName)
    {
        return _commands[commandName].Value;
    }

    public void Execute(string commandName)
    {
        GetCommand(commandName).Execute();
    }

    public void Undo(string commandName)
    {
        GetCommand(commandName).Undo();
    }
}


public class A
{
    public void DoA()
    {
    }

    public void UndoA()
    {
    }
}

public class B
{
    public void DoB()
    {
    }

    public void UndoB()
    {
    }
}

如您所见,即使您有多个方法(执行、撤消等),也无需实现接口。请注意,Execute 和 Undo 方法可能属于不同的类。您可以自由地以感觉更自然的方式构建代码,并且仍然可以使用命令模式。

于 2012-01-09T12:49:56.587 回答
4

您可以使用 aDictionary将字母/字符映射到相关ICommand实现。就像是:

public class CommandFactory
{
    private readonly Dictionary<string, ICommand> mCommands = new Dictionary<string,ICommand>(StringComparer.OrdinalIgnoreCase);

    public void RegisterCommand<TCommand>(string commandKey) where TCommand : ICommand, new()
    {
        // Instantiate the command
        ICommand command = new TCommand();

        // Add to the collection
        mCommands.Add(commandKey, command);
    }

    public void ExecuteCommand(string commandKey)
    {
        // See if the command exists
        ICommand command;
        if (!mCommands.TryGetValue(commandKey, out command))
        {
            // TODO: Handle invalid command key
        }

        // Execute the command
        command.Execute();
    }
}

使用它,您可以注册命令类型并将它们映射到string基于 - 的键,并允许它们被实例化并更通用地执行。您可以通过仅在首次使用命令类型时实例化它们来提高性能。

编辑

为了回答您的评论,仅在执行时实例化,您可以执行以下操作:

public class CommandDetails<T> where T : ICommand, new()
{
    private ICommand mCommand;

    public ICommand GetCommand()
    {
        if (/* Determine if the command has been instantiated */)
        {
            // Instantiate the command
            mCommand = new T();
        }

        return mCommand;
    }
}

public void ExecuteCommand(...)
{
    // See if the command exists
    CommandDetails details;
    // ...

    // Get the command
    // Note: If we haven't got the command yet, this will instantiate it for us.
    ICommand command = details.GetCommand();

    // ...
}
于 2012-01-09T12:32:36.527 回答
1

您可以考虑要求您的工作提供它自己的 ICommand:

interface IJob 
{
  ICommand Command { get; }
}

public class JobA : IJob
{
  private readonly ICommand _command = new CommandA();
  public ICommand Command { get { return _command; } }
}

然后,您可以执行以下操作,而不是打开 jobCode:

job.Command.Execute();
于 2012-01-09T12:30:00.477 回答